OpenDesign Specification for .dwg files - c#

I've been working with OpenDesign Specification for .dwg files about two weeks. And now, i've got all information except non-entity object and entity object. Maybe i can't understand how this information written. Concretely i need to know how to differ non-entity object and entity object. Work on C#. http://opendesign.com/files/guestdownloads/OpenDesign_Specification_for_.dwg_files.pdf on the page 98.
This is how i found out non-entity object format:
private bool ReadNonEntityObject(FileReader fileReader, DWGVersion version, long handle, long fileLoc)
{
long oldPos = fileReader.BufferPosition;
BaseTypes bReader = new BaseTypes(fileReader);
fileReader.SeekAbsolute(fileLoc);
var size = bReader.GetModularShort();
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2010))
{
var HandleSize = bReader.GetModularChar(false);
}
var objectType = bReader.GetObjectType(version);
Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(objectType), 0).Substring(0, 2));
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2000) && version.IsEarlier(DWGVersion.VersionEnum.R2010))
{
var ObjectSize = bReader.GetLongRaw();
}
var handl = bReader.GetHandle();
if (handl != handle)
throw new Exception("DWG file is corrupted or incorrect");
var extendedSize = bReader.GetShort();
int size1 = 0;
bool isGraphic = fileReader.GetBits(1, true)[0];
if (isGraphic)
size1 = bReader.GetLongRaw();
if (extendedSize != 0)
{
var appHandle = bReader.GetHandle();
var endPos = fileReader.BufferPosition + extendedSize;
string data = "";//DEBUG for testing
while (fileReader.BufferPosition < endPos)
{
int byteCode = bReader.GetByteRaw();
object val = null;
switch (byteCode) //TODO add all byteCode
{
case 0:
{
if (version.IsEarlier(DWGVersion.VersionEnum.R2007))
{
int N = bReader.GetByteRaw();
var codePage = bReader.GetShortRaw();
val = bReader.GetStringAscii(N);
}
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2007))
{
//TODO
}
}
break;
case 1:
val = bReader.GetText();
break;
case 8:
{
break;
}
case 2:
val = bReader.GetCharAscii() == 0 ? '{' : '}';
break;
case 40:
bReader.Get3DDouble();
break;
case 145:
{
val = bReader.GetDouble();
break;
}
case 70:
val = bReader.GetShortRaw();
break;
case 71:
val = bReader.GetLongRaw();
break;
default:
val = "";
break;
}
data += val + " ";
//Console.WriteLine(data);
}
}
if (version.Equals(DWGVersion.VersionEnum.R13_R14))
{
var DataSize = bReader.GetLongRaw();
var persistentNum = bReader.GetByteRaw();
}
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2004))
{
}
fileReader.SeekAbsolute(oldPos);
return true;
}

There is no isGraphic bit in non-entity object.
Extended data only. it is loop-like, see page 254.
in my experience most types - are entity objects.
i have base class for object and some heder reader in it. Many types extends from each other.
Use crc check, where it is for check you proof.

Related

c# convert byte[] to byte but keep value the same

So i have a program that communicates through tcp, the server was already done, but i don't understand how to convert the byte[] to byte but keeping the value the same.
public static List<byte[]> Separate(byte[] source, byte[] separator)
{
List<byte[]> list = new List<byte[]>();
int num = 0;
byte[] array;
for (int i = 0; i < source.Length; i++)
{
if (Equals(source, separator, i))
{
array = new byte[i - num];
Array.Copy(source, num, array, 0, array.Length);
list.Add(array);
num = i + separator.Length;
i += separator.Length - 1;
}
}
array = new byte[source.Length - num];
Array.Copy(source, num, array, 0, array.Length);
list.Add(array);
return list;
}
private static bool Equals(byte[] source, byte[] separator, int index)
{
for (int i = 0; i < separator.Length; i++)
{
if (index + i >= source.Length || source[index + i] != separator[i])
{
return false;
}
}
return true;
}
private static byte[] delimiter = Encoding.ASCII.GetBytes("<EOM>");
private static byte[] end = Encoding.ASCII.GetBytes("<EOF>");
public static IServerPacket BuildPacket(byte[] _data)
{
try
{
List<byte[]> list = new List<byte[]> { _data };
byte b = list[0].ToList().GetRange(0, 1)[0];
IServerPacket result = null;
List<byte> list2 = list[0].ToList();
list2.RemoveRange(0, 6);
list[0] = list2.ToArray();
list = Separate(Separate(list[0], end)[0], delimiter);
//printing list[0][0] here gives me 50 instead of 2
switch (b)
{
case 1:
result = new Start(1, list[0][0]);
break;
case 2:
result = new Stop();
break;
case 3:
result = new MouseEvnt(list[0][0], list[1][0], list[2], list[3], list[4][0]);
break;
case 4:
result = new KeyEvnt(list[0][0], list[1][0]);
break;
}
return result;
}
catch
{
}
return null;
}
what i'm sending with the server : 1<EOM>2<EOM>3<EOM>4<EOM>5<EOM>6<EOM> , printing list[0][0] will give me 50 instead of 2. tried everything but i just couldn't make it work..
You need to be MUCH more aware of the types you already have and resulting types of each expression within a statement. So much of the original code in this method was simply not doing anything productive at all, just to get back to the original value you already had. There's no reason for any of that code in the question to ever convert those byte arrays to List.
public static IServerPacket BuildPacket(byte[] _data)
{
byte b = _data[0];
IServerPacket result = null;
switch ((char)b)
{
case '1':
result = new Start(1, b);
break;
case '2':
result = new Stop();
break;
case '3':
result = new MouseEvnt(b, _data[1], _data[2], _data[3], _data[4]);
break;
case '4':
result = new KeyEvnt(b, _data[1]);
break;
}
return result;
}
Alternatively you can keep the ascii values, which might be more efficient:
public static IServerPacket BuildPacket(byte[] _data)
{
byte b = _data[0];
IServerPacket result = null;
switch (b)
{
case 49:
result = new Start(1, b);
break;
case 50:
result = new Stop();
break;
case 51:
result = new MouseEvnt(b, _data[1], _data[2], _data[3], _data[4]);
break;
case 52:
result = new KeyEvnt(b, _data[1]);
break;
}
return result;
}
Not sure on the event objects, since I can't see how they work, but I suspect this is pretty close.

Marshal a va_list

I have the following code:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void PanicFuncDelegate(string str, IntPtr args);
private void PanicFunc(string str, IntPtr args)
{
LogFunc("PANIC", str, args);
}
public void LogFunc(string severity, string str, IntPtr args)
{
vprintf($"[{severity}] "+ str,args);
}
[DllImport("libc.so.6")]
private static extern int vprintf(string format, IntPtr args);
This prints to the console the messages correctly formatted. I want to retrieve the values from args to use them in my own logger.
If I try to get the value of each pointer from the array in args (as suggested here: Marshal va_list in C# delegate) I get segmentation fault.
Any suggestions?
I have a function call with this working, here's what I do:
For the DLLImport I use an __arglist to marshall to the va_list,
[DllImport("libc.so.6")]
private static extern int vprintf(string format, __arglist);
Then when calling the function I create the __arglist,
vprintf(string format, __arglist(arg1, arg2, arg3...))
Ofcourse you would need to either call the function with all the arguments statically or build that __arglist dynamically, I don't have the code here but it's possible.
I wonder if you get a segmentation fault because the elements in the object[] are not pinned? Maybe if you pin the object[] and all elements within that would help? Just a guess though.
Just think on how C program gets variables from va_list, and there is the solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace VaTest
{
class Program
{
static void Main(string[] args)
{
MarshalVaArgs(vaList => vprintf("%c%d%s", vaList), false, 'a', 123, "bc");
}
[DllImport("msvcrt")] //windows
//[DllImport("c")] //linux
private static extern int vprintf(string format, IntPtr vaList);
private static int IntSizeOf(Type t)
{
return (Marshal.SizeOf(t) + IntPtr.Size - 1) & ~(IntPtr.Size - 1);
}
public static void MarshalVaArgs(Action<IntPtr> action, bool? isUnicode, params object[] args)
{
var sizes = new int[args.Length];
for (var i = 0; i < args.Length; i++)
{
sizes[i] = args[i] is string ? IntPtr.Size : IntSizeOf(args[i].GetType());
}
var allocs = new List<IntPtr>();
var offset = 0;
var result = Marshal.AllocHGlobal(sizes.Sum());
allocs.Add(result);
for (var i = 0; i < args.Length; i++)
{
if (args[i] is string)
{
var s = (string)args[i];
var data = default(IntPtr);
if (isUnicode.HasValue)
{
if (isUnicode.Value)
{
data = Marshal.StringToHGlobalUni(s);
}
else
{
data = Marshal.StringToHGlobalAnsi(s);
}
}
else
{
data = Marshal.StringToHGlobalAuto(s);
}
allocs.Add(data);
Marshal.WriteIntPtr(result, offset, data);
offset += sizes[i];
}
else
{
Marshal.StructureToPtr(args[i], result + offset, false);
offset += sizes[i];
}
}
action(result);
foreach (var ptr in allocs)
{
Marshal.FreeHGlobal(ptr);
}
}
}
}
The code is written and tested with .NET Core 3.0 preview 5, compatible with .NET Framework 4.0 and C# 3.0.
Outputs:
a123bc
As this isn't solved yet i post a long solution that worked for me.
I found the solution in an abandoned project
https://github.com/GoaLitiuM/libobs-sharp
Use like this (tested with FFmpeg):
var objects = va_list_Helper.VaListToArray(format, va_List_Ptr);
// format: frame=%4d QP=%.2f NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s
// format (filled): frame= 3 QP=13.00 NAL=0 Slice:B Poc:4 I:0 P:8 SKIP:912 size=32 bytes
// va_List objects: 3, 13, 0, 'B', 4, 0, 8, 912, 32
The classes needed:
public class va_list_Helper
{
public static unsafe object[] VaListToArray(string format, byte* va_list)
{
var vaList = new va_list((IntPtr)va_list);
return vaList.GetObjectsByFormat(format);
}
}
public static class Printf
{
// used
public static string[] GetFormatSpecifiers(string format)
{
if (format.IndexOf('%') == -1)
return null;
// find specifiers from format string
List<int> indices = new List<int>();
for (int j = 0; j < format.Length; j++)
{
j = format.IndexOf('%', j);
if (j == -1)
break;
indices.Add(j);
if (format[j + 1] == '%') // ignore "%%"
j++;
}
if (indices.Count == 0)
return null;
List<string> formats = new List<string>(indices.Count);
for (int mi = 0; mi < indices.Count; mi++)
{
string formatSpecifier = format.Substring(indices[mi], (mi + 1 < indices.Count ? indices[mi + 1] : format.Length) - indices[mi]);
if (!string.IsNullOrWhiteSpace(formatSpecifier))
formats.Add(formatSpecifier);
}
return formats.ToArray();
}
public class FormatSpecificationInfo
{
public string specification;
//public int parameter;
public char type;
public int width;
public int precision;
public FormatFlags flags;
};
[Flags]
public enum FormatFlags
{
// Type length
IsLong = 0x0001, // l
IsLongLong = 0x0002, // ll
IsShort = 0x0004, // h
IsChar = 0x0008, // hh
IsLongDouble = 0x0016, // L
// Flags
LeftAlign = 0x0100, // '-' left align within the width
Sign = 0x0200, // '+' use - or + signs for signed types
Alternate = 0x0400, // '#' prefix non-zero values with hex types
ZeroPad = 0x0800, // '0' pad with zeros
Blank = 0x1000, // ' ' pad sign with blank
Grouping = 0x2000, // '\' group by thousands
ArchSize = 0x4000, // '?' use arch precision
// Dynamic parameters
DynamicWidth = 0x10000,
DynamicPrecision = 0x20000,
};
// used
public static FormatSpecificationInfo GetFormatSpecifierInfo(string specification)
{
if (string.IsNullOrWhiteSpace(specification))
return null;
FormatSpecificationInfo info = new FormatSpecificationInfo()
{
type = '\0',
width = int.MinValue,
precision = 6,
};
string width = "";
string precision = "";
int start = -1;
int fsLength = 1;
// TODO: parse parameter index
for (int i = 0; i < specification.Length && info.type == '\0'; i++)
{
char c = specification[i];
switch (c)
{
case '%':
if (start == -1)
start = i;
else
info.type = c;
info.specification = specification.Substring(start, i + 1 - start);
fsLength = i + 1;
break;
// flags
case '-':
info.flags |= FormatFlags.LeftAlign;
break;
case '+':
info.flags |= FormatFlags.Sign;
break;
case ' ':
info.flags |= FormatFlags.Blank;
break;
case '#':
info.flags |= FormatFlags.Alternate;
break;
case '\'':
info.flags |= FormatFlags.Grouping;
break;
case '?':
info.flags |= FormatFlags.ArchSize;
break;
// precision
case '.':
{
for (int j = i + 1; j < specification.Length; j++)
{
if (specification[j] == '*')
info.flags |= FormatFlags.DynamicPrecision;
else if (char.IsNumber(specification[j]))
precision += specification[j];
else
break;
i++;
}
}
break;
// length flags
case 'h':
info.flags += (int)FormatFlags.IsShort;
break;
case 'l':
info.flags += (int)FormatFlags.IsLong;
break;
case 'L':
info.flags |= FormatFlags.IsLongDouble;
break;
case 'z':
case 'j':
case 't':
// not supported
break;
// dynamic width
case '*':
info.flags |= FormatFlags.DynamicWidth;
break;
default:
{
if (char.IsNumber(c))
{
if (width == "" && c == '0')
info.flags |= FormatFlags.ZeroPad;
else
width += c;
}
else if (char.IsLetter(c) && info.type == '\0')
{
info.type = c;
info.specification = specification.Substring(start, i + 1 - start);
fsLength = i + 1;
}
}
break;
}
}
// sign overrides space
if (info.flags.HasFlag(FormatFlags.Sign) && info.flags.HasFlag(FormatFlags.Blank))
info.flags &= ~FormatFlags.Blank;
if (info.flags.HasFlag(FormatFlags.LeftAlign) && info.flags.HasFlag(FormatFlags.ZeroPad))
info.flags &= ~FormatFlags.ZeroPad;
// unsupported precision for these types
if (info.type == 's' ||
info.type == 'c' ||
Char.ToUpper(info.type) == 'X' ||
info.type == 'o')
{
info.precision = int.MinValue;
}
if (!string.IsNullOrWhiteSpace(precision))
info.precision = Convert.ToInt32(precision);
if (!string.IsNullOrWhiteSpace(width))
info.width = Convert.ToInt32(width);
return info;
}
}
public class va_list
{
internal IntPtr instance; //unmanaged pointer to va_list
public va_list(IntPtr ptr)
{
instance = ptr;
}
/// <summary> Returns unmanaged pointer to argument list. </summary>
public IntPtr GetPointer()
{
return instance;
}
/// <summary> Returns array of objects with help of printf format string. </summary>
/// <param name="format"> printf format string. </param>
public object[] GetObjectsByFormat(string format)
{
return GetObjectsByFormat(format, this);
}
public static unsafe object[] GetObjectsByFormat(string format, va_list va_list)
{
string[] formatSpecifiers = Printf.GetFormatSpecifiers(format);
if (formatSpecifiers == null || va_list == null || va_list.GetPointer() == IntPtr.Zero)
return null;
IntPtr args = va_list.GetPointer();
List<object> objects = new List<object>(formatSpecifiers.Length);
//var bytesDebug = new byte[format.Length];
//Marshal.Copy(va_list.GetPointer(), bytesDebug, 0, bytesDebug.Length);
int offset = 0;
foreach (string spec in formatSpecifiers)
{
var info = Printf.GetFormatSpecifierInfo(spec);
if (info.type == '\0')
continue;
// dynamic width and precision arguments
// these are stored in stack before the actual value
if (info.flags.HasFlag(Printf.FormatFlags.DynamicWidth))
{
int widthArg = Marshal.ReadInt32(args, offset);
objects.Add(widthArg);
offset += Marshal.SizeOf(typeof(IntPtr));
}
if (info.flags.HasFlag(Printf.FormatFlags.DynamicPrecision))
{
int precArg = Marshal.ReadInt32(args, offset);
objects.Add(precArg);
offset += Marshal.SizeOf(typeof(IntPtr));
}
int iSize = info.flags.HasFlag(Printf.FormatFlags.IsLongLong)
? Marshal.SizeOf(typeof(Int64)) : Marshal.SizeOf(typeof(IntPtr));
// marshal objects from pointer
switch (info.type)
{
// 8/16-bit integers
// char / wchar_t (promoted to int)
case 'c':
char c = (char)Marshal.ReadByte(args, offset);
objects.Add(c);
//offset += Marshal.SizeOf(typeof(Int32));
offset += Marshal.SizeOf(typeof(IntPtr));
break;
// signed integers
case 'd':
case 'i':
{
if (info.flags.HasFlag(Printf.FormatFlags.IsShort)) // h
{
short sh = (short)Marshal.ReadInt32(args, offset);
objects.Add(sh);
offset += Marshal.SizeOf(typeof(Int32));
}
else if (info.flags.HasFlag(Printf.FormatFlags.IsLongLong)) // ll
{
long l = Marshal.ReadInt64(args, offset);
objects.Add(l);
offset += iSize;
}
else // int and long types
{
var i = Marshal.ReadInt32(args, offset);
objects.Add(i);
offset += iSize;
}
}
break;
// unsigned integers
case 'u':
case 'o':
case 'x':
case 'X':
{
if (info.flags.HasFlag(Printf.FormatFlags.IsShort)) // h
{
ushort su = (ushort)Marshal.ReadInt32(args, offset);
objects.Add(su);
offset += Marshal.SizeOf(typeof(Int32));
}
else if (info.flags.HasFlag(Printf.FormatFlags.IsLongLong)) // ll
{
ulong lu = (ulong)(long)Marshal.ReadInt64(args, offset);
objects.Add(lu);
offset += iSize;
}
else // uint and ulong types
{
uint u = (uint)Marshal.ReadInt32(args, offset);
objects.Add(u);
offset += iSize;
}
}
break;
// floating-point types
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
{
if (info.flags.HasFlag(Printf.FormatFlags.IsLongDouble)) // L
{
// not really supported but read it as long
long lfi = Marshal.ReadInt64(args, offset);
double d = *(double*)(void*)&lfi;
objects.Add(d);
offset += Marshal.SizeOf(typeof(double));
}
else // double
{
long lfi = Marshal.ReadInt64(args, offset);
double d = *(double*)(void*)&lfi;
objects.Add(d);
offset += Marshal.SizeOf(typeof(double));
}
}
break;
// string
case 's':
{
string s = null;
// same:
//var addr1 = new IntPtr(args.ToInt64() + offset);
//var intPtr4 = Marshal.ReadIntPtr(addr1);
var intPtr3 = Marshal.ReadIntPtr(args, offset);
if (info.flags.HasFlag(Printf.FormatFlags.IsLong))
{
s = Marshal.PtrToStringUni(intPtr3);
}
else
{
s = Marshal.PtrToStringAnsi(intPtr3);
}
objects.Add(s);
offset += Marshal.SizeOf(typeof(IntPtr));
}
break;
// pointer
case 'p':
IntPtr ptr = Marshal.ReadIntPtr(args, offset);
objects.Add(ptr);
offset += Marshal.SizeOf(typeof(IntPtr));
break;
// non-marshallable types, ignored
case ' ':
case '%':
case 'n':
break;
default:
throw new ApplicationException("printf specifier '%" + info.type + "' not supported");
}
}
return objects.ToArray();
}
}

How can I let a user input one of the shift values and then output the corresponding string to a text file?

using System;
public class ReadWriteTxt // Read and write to/from text files
{
public static string cipherTxt()
{
return System.IO.File.ReadAllText(#"myfile1");
}
internal static void decipherTxt(string result)
{
System.IO.File.WriteAllText(#"myfile2", result);
}
}
public class LetterArray
{
internal static string[] Alphabet()
{
var letterValues = new string[26];
letterValues[0] = "A";
letterValues[1] = "B";
letterValues[2] = "C";
letterValues[3] = "D";
letterValues[4] = "E";
letterValues[5] = "F";
letterValues[6] = "G";
letterValues[7] = "H";
letterValues[8] = "I";
letterValues[9] = "J";
letterValues[10] = "K";
letterValues[11] = "L";
letterValues[12] = "M";
letterValues[13] = "N";
letterValues[14] = "O";
letterValues[15] = "P";
letterValues[16] = "Q";
letterValues[17] = "R";
letterValues[18] = "S";
letterValues[19] = "T";
letterValues[20] = "U";
letterValues[21] = "V";
letterValues[22] = "W";
letterValues[23] = "X";
letterValues[24] = "Y";
letterValues[25] = "Z";
return letterValues;
}
}
public class Decipher
{
public static void Main() //Main method
{
int res = 34;
string[] letterValues = LetterArray.Alphabet();
//Create for loop that runs through every possible shift value
for (int shift = 0; shift <= 25; shift++)
{
Console.WriteLine("\nShift Value = " + shift + ": ");
// For each character in the text file
foreach (var ch in ReadWriteTxt.cipherTxt())
{
string result = string.Empty;
if (ch == ' ')
{
}
else
{
for (int i = 0; i <= 25; i++)
{
if ((ch.ToString().ToUpper()) == letterValues[i])
{
res = i;
if (shift > res)
{
// print results out
Console.Write(letterValues[26 - (shift - res)][0]);
}
else
{
Console.Write(letterValues[res - shift][0]);
}
}
}
ReadWriteTxt.decipherTxt(result);
}
}
}
}
}
I'm working on a Caesar Cipher program that decrypts cipher text that it reads in from a file.
It lists all the possible shifts throughout the alphabet.
I need to be able allow the user to enter the 'correct' shift value (e.g. the one closest to what the decrypted text should translate too) and then have the corresponding string written to a file.
What is the best to go about this?
P.S. My understanding of C# is a bit basic so please be gentle with me ;).

Read & write text to a separate file on the hard drive

Having a problem with my code here. My code is supposed to (what I want it to do) is after the game ends a spritefont appears that allows you to enter text and once that text is entered then it would write that score to the text file. But of course it does not do that. If anyone could help, would be grand.
EDIT
This is what I am using to try and input text after the game is over (Game is Space Invaders) Perhaps there is something wrong here also.
SpriteFont Label;
string txt = ".";
Keys PrevKey;
string[] HighScores = new string[5];
int count = 0;
KeyboardState ks = Keyboard.GetState();
Keys[] k = ks.GetPressedKeys();
Keys tempKey = Keys.None;
string keyChar = "";
foreach (Keys q in k)
{
Keys currentKey = q;
if (ks.IsKeyUp(PrevKey))
{
if (!(q == Keys.None))
{
switch (q)
{
case Keys.Space: keyChar = " "; break;
case Keys.Delete: txt = ""; break;
case Keys.Back: txt = txt.Remove(txt.Length - 1); break;
case Keys.Enter: HighScores[count] = txt; count++; txt = "";
if (count == 5) count = 0; break;
case Keys.End: WriteScores(); break;
case Keys.Home: ReadScores(); break;
default: keyChar = q.ToString(); break;
}
txt += keyChar;
}
}
if (currentKey != Keys.None && ks.IsKeyDown(currentKey))
{
tempKey = currentKey;
}
}
PrevKey = tempKey;
base.Update(gameTime);
}
}
}
}
public void WriteScores()
{
StreamWriter Rite = new StreamWriter(#"C:\TheScores.txt");
for (int i = 0; i < HighScores.Length; i++)
{
Rite.WriteLine(HighScores[i]);
}
Rite.Close();
}
public void ReadScores()
{
if (File.Exists(#"C:\TheHighScores.txt"))
{
StreamReader Reed = new StreamReader(#"C:\TheScores.txt");
for (int i = 0; i < HighScores.Length; i++)
{
txt += Reed.ReadLine() + "\n";
}
Reed.Close();
}
}
Change the path to a user folder like Documents or AppData. Your code as it is will throw an access violation for insufficient permissions unless you run your program as administrator, as the root of C:\ is only available from an elevated context.

Session not working in Windows service application?

i am trying to use Session["emailcc3"] in windows service application ..but it shows me an error session not available in this context....is there any alternative way to do that??
THIS IS MY CODE:
foreach (DataRow newRow in employee.Rows)
{
num = num - 1;
if (num == 4)
{
Session["emailto"] = newRow["EMAILID"].ToString();
}
if (num == 3)
{
Session["emailcc1"] = newRow["EMAILID"].ToString();
}
if (num == 2)
{
Session["emailcc2"] = newRow["EMAILID"].ToString();
}
if (num == 1)
{
Session["emailcc3"] = newRow["EMAILID"].ToString();
}
}
string emailto = Session["emailto"].ToString();
string emailcc1 = Session["emailcc1"].ToString();
string emailcc2 = Session["emailcc2"].ToString();
string emailcc3 = Session["emailcc3"].ToString();
If I took a wild guess, I think all that you want is this:
string emailto = null;
string emailcc1 = null;
string emailcc2 = null;
string emailcc3 = null;
foreach (DataRow newRow in employee.Rows)
{
num = num - 1;
switch (num)
{
case 4:
emailto = newRow["EMAILID"].ToString();
break;
case 3:
emailcc1 = newRow["EMAILID"].ToString();
break;
case 2:
emailcc2 = newRow["EMAILID"].ToString();
break;
case 1:
emailcc3 = newRow["EMAILID"].ToString();
break;
default:
//Do something here?
}
}
I'm not sure why you were using Session at all - unless you were using it because it allows you to declare variables on the fly, as it were.

Categories