Beispiel #1
0
        private void ICD_NewChat(int clientID, HEADER obj)
        {
            ChatRoom room   = new ChatRoom();
            int      chatID = room.CreateNewChat((ChatRoomInfo)obj);

            mRooms[chatID] = room;
        }
Beispiel #2
0
        private void ProcTaskListTime(HEADER obj)
        {
            mCount = 0;
            ICD.WorkList msg = (ICD.WorkList)obj;

            HEADER msgHis = new HEADER();

            msgHis.FillClientHeader(DEF.CMD_TaskHistory);

            foreach (Work item in msg.works)
            {
                if (mTracks.ContainsKey(item.recordID))
                {
                    continue;
                }

                TrackingInfo info = new TrackingInfo();
                info.workBase          = item;
                info.his               = null;
                mTracks[item.recordID] = info;
                mCount++;

                msgHis.ext1 = item.recordID.ToString();
                ICDPacketMgr.GetInst().sendMsgToServer(msgHis);
            }
        }
Beispiel #3
0
        private HEADER CreateICD_onServer(HEADER head)
        {
            switch (head.msgID)
            {
            case DEF.CMD_TaskNew:
                return(new WorkList());

            case DEF.CMD_TaskEdit:
                return(new WorkHistoryList());

            case DEF.CMD_TaskBaseList:
            case DEF.CMD_TaskHistory:
            case DEF.CMD_TaskIDList:
            case DEF.CMD_ChatRoomList:
            case DEF.CMD_UserList:
                return(new HEADER());

            case DEF.CMD_NewChat:
            case DEF.CMD_ChatMsg:
            case DEF.CMD_AddChatUsers:
            case DEF.CMD_DelChatUsers:
            case DEF.CMD_ShowChat:
            case DEF.CMD_HideChat:
            case DEF.CMD_ChatRoomInfo:
            case DEF.CMD_ChatMsgAll:
                return(new ChatRoomInfo());

            case DEF.CMD_NewUser:
            case DEF.CMD_Login:
                return(new User());
            }
            LOG.warn();
            return(null);
        }
Beispiel #4
0
        private void ICD_ChatRoomList(int clientID, HEADER obj)
        {
            List <RoomInfo> vec = new List <RoomInfo>();

            foreach (var item in mRooms)
            {
                if (!item.Value.IsUser(obj.msgUser))
                {
                    continue;
                }

                RoomInfo     info = new RoomInfo();
                ChatRoomInfo room = item.Value.GetRoomInfo();
                info.recordID = room.body.recordID;
                info.state    = item.Value.GetUserState(obj.msgUser);
                info.users    = room.body.users;
                vec.Add(info);
            }

            if (vec.Count > 0)
            {
                ChatRoomList msg = new ChatRoomList(1);
                msg.FillServerHeader(DEF.CMD_ChatRoomList, 0);
                msg.body = vec.ToArray();
                sendMsg(obj.msgUser, msg);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Loads a Halo 2 Map file using the specified <see cref="HaloIO"/> instance.
        /// </summary>
        /// <param name="io">The <see cref="HaloIO"/> used to access the map file.</param>
        private void LoadMap(HaloIO io)
        {
            //Open
            io.OpenIO();

            //Read Header
            io.Position = 0;
            header      = io.In.ReadStructure <HEADER>();

            //Prepare Index Table Header
            io.Position = header.IndexOffset;
            index       = io.In.ReadStructure <INDEX>();

            //Load File Names
            LoadFileNamesInfo(io);

            //Load Tag Objects
            LoadTagsInfo(io);

            //Load Index Objects
            LoadObjectInfo(io);

            //Load Strings
            LoadStringsInfo(io);

            //Fix SBSPs and LTMPs
            FixSpecialEntries(io);

            //Close Map
            io.CloseIO();
        }
Beispiel #6
0
            public new byte[] Serialize()
            {
                List <byte> ary  = new List <byte>();
                HEADER      head = new HEADER();

                head.msgSOF  = msgSOF;
                head.msgID   = msgID;
                head.msgSize = msgSize;
                head.msgType = msgType;
                head.msgErr  = msgErr;
                head.msgUser = msgUser;
                head.msgTime = msgTime;
                head.ext1    = ext1;
                head.ext2    = ext2;

                ary.AddRange(head.Serialize());

                ary.AddRange(BitConverter.GetBytes(msgCount));

                for (int i = 0; i < msgCount; ++i)
                {
                    int    msgSize = Marshal.SizeOf(typeof(ChatMsg));
                    byte[] src     = new byte[msgSize];
                    var    gch     = GCHandle.Alloc(src, GCHandleType.Pinned);
                    var    pBuffer = gch.AddrOfPinnedObject();
                    Marshal.StructureToPtr(msgs[i], pBuffer, false);
                    gch.Free();
                    ary.AddRange(src);
                }

                return(ary.ToArray());
            }
Beispiel #7
0
        private void ICD_ProcWorkHistory(int clientID, HEADER obj)
        {
            string    user   = obj.msgUser;
            int       taskID = int.Parse(obj.ext1);
            DataTable table  = DatabaseMgr.GetTaskHistory(taskID);

            if (table == null)
            {
                return;
            }

            List <WorkHistory> vec = new List <WorkHistory>();

            foreach (DataRow item in table.Rows)
            {
                WorkHistory his = new WorkHistory();
                his.recordID   = (int)item["recordID"];
                his.taskID     = (int)item["taskID"];
                his.time       = item["time"].ToString();;
                his.editor     = item["user"].ToString();
                his.columnName = item["columnName"].ToString();
                his.fromInfo   = item["fromInfo"].ToString();
                his.toInfo     = item["toInfo"].ToString();

                vec.Add(his);
            }

            WorkHistoryList msg = new WorkHistoryList();

            msg.FillServerHeader(DEF.CMD_TaskHistory, 0);
            msg.workHistory = vec.ToArray();
            sendMsg(user, msg);
        }
Beispiel #8
0
        private void ICD_Login(int clientID, HEADER obj)
        {
            User    msg  = obj as User;
            DataRow row  = DatabaseMgr.GetUserInfo(msg.userID);
            User    pack = new User();

            pack.FillServerHeader(DEF.CMD_Login);
            if (row != null)
            {
                if (row["password"].ToString() == msg.userPW)
                {
                    AddUser(clientID, msg.userID);
                    pack.userID = row["recordID"].ToString();
                    pack.userPW = row["password"].ToString();
                }
                else
                {
                    pack.msgErr = DEF.ERR_WorngPW;
                }
            }
            else
            {
                pack.msgErr = DEF.ERR_NoID;
            }

            ICDPacketMgr.GetInst().sendMsgToClient(clientID, pack);
        }
Beispiel #9
0
        protected bool ParseHeader(string p_strMsg, ref XmlDocument p_xml, ref HEADER p_header)
        {
            try
            {
                p_xml.LoadXml(p_strMsg);
                XmlElement headerTag = p_xml.SelectSingleNode("WRH_MSG/HEADER") as XmlElement;

                XmlElement element = headerTag.SelectSingleNode("Category") as XmlElement;
                p_header.Category = element.InnerText;

                element            = headerTag.SelectSingleNode("CommandNo") as XmlElement;
                p_header.CommandNo = element.InnerText;

                element          = headerTag.SelectSingleNode("Command") as XmlElement;
                p_header.Command = element.InnerText;

                element = headerTag.SelectSingleNode("RequesterId") as XmlElement;
                p_header.RequesterId = element.InnerText;

                element           = headerTag.SelectSingleNode("DateTime") as XmlElement;
                p_header.DateTime = element.InnerText;
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 메세지 헤더 파싱중 예외가 발생하였습니다.[{1}]", m_nThreadNo, p_strMsg));
                return(false);
            }

            return(true);
        }
Beispiel #10
0
            public new void Deserialize(ref byte[] data)
            {
                msgSOF  = BitConverter.ToInt32(data, 0);
                msgID   = BitConverter.ToInt32(data, 4);
                msgSize = BitConverter.ToInt32(data, 8);
                msgType = BitConverter.ToInt32(data, 12);
                msgErr  = BitConverter.ToInt32(data, 16);

                msgUser = Encoding.ASCII.GetString(data, 20, 50).TrimEnd('\0');
                msgTime = Encoding.ASCII.GetString(data, 70, 50).TrimEnd('\0');
                ext1    = Encoding.ASCII.GetString(data, 120, 50).TrimEnd('\0');
                ext2    = Encoding.ASCII.GetString(data, 170, 50).TrimEnd('\0');

                int headLen = HEADER.HeaderSize();

                msgCount = BitConverter.ToInt32(data, headLen);
                msgs     = new ChatMsg[msgCount];
                for (int i = 0; i < msgCount; ++i)
                {
                    int    msgSize = Marshal.SizeOf(typeof(ChatMsg));
                    byte[] dest    = new byte[msgSize];
                    int    off     = headLen + 4 + (i * msgSize);
                    Array.Copy(data, off, dest, 0, msgSize);

                    msgs[i] = new ChatMsg();
                    var gch = GCHandle.Alloc(dest, GCHandleType.Pinned);
                    Marshal.PtrToStructure(gch.AddrOfPinnedObject(), msgs[i]);
                    gch.Free();
                }
            }
Beispiel #11
0
            public override void Deserialize(ref byte[] data)
            {
                int headSize = HEADER.HeaderSize();
                int bodySize = data.Length - headSize;

                byte[] headBuf = new byte[headSize];
                Array.Copy(data, 0, headBuf, 0, headSize);
                HEADER head = new HEADER();

                head.Deserialize(ref headBuf);

                msgID   = head.msgID;
                msgSize = head.msgSize;
                msgSOF  = head.msgSOF;
                msgType = head.msgType;
                msgErr  = head.msgErr;
                msgUser = head.msgUser;
                msgTime = head.msgTime;
                ext1    = head.ext1;
                ext2    = head.ext2;

                byte[] bodyBuf = new byte[bodySize];
                Array.Copy(data, headSize, bodyBuf, 0, bodySize);
                BinaryFormatter bf = new BinaryFormatter();

                using (MemoryStream ms = new MemoryStream(bodyBuf))
                {
                    workHistory = (WorkHistory[])bf.Deserialize(ms);
                }
            }
Beispiel #12
0
            static public HEADER ConvertBytesToICDMessage(byte[] buf)
            {
                long nRecvLen = buf.Length;
                int  headSize = ICD.HEADER.HeaderSize();

                if (nRecvLen < headSize)
                {
                    return(null);
                }

                byte[] headBuf = new byte[headSize];
                Array.Copy(buf, 0, headBuf, 0, headSize);
                HEADER head = new HEADER();

                head.Deserialize(ref headBuf);
                if (head.msgSOF != ICD.DEF.MAGIC_SOF)
                {
                    LOG.warn();
                    return(null);
                }

                int msgSize = head.msgSize;

                if (nRecvLen < msgSize)
                {
                    return(null);
                }

                byte[] msgBuf  = new byte[msgSize];
                HEADER realMsg = CreateRealMessage(head);

                realMsg.Deserialize(ref msgBuf);
                return(realMsg);
            }
Beispiel #13
0
        private void ICD_Logout(int clientID, HEADER obj)
        {
            DelUser(obj.msgUser);
            HEADER pack = new HEADER();

            pack.FillServerHeader(DEF.CMD_Logout);
            ICDPacketMgr.GetInst().sendMsgToClient(clientID, pack);
        }
Beispiel #14
0
        public static void testExportHead(HEADER data)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(HEADER));

            using (TextWriter writer = new StreamWriter("test.xml"))
            {
                serializer.Serialize(writer, data);
            }
        }
Beispiel #15
0
        private void SerializeHeader(byte[] buffer, ushort size, ushort command)
        {
            HEADER        hEADER        = new HEADER(size + 5, command);
            RawSerializer rawSerializer = new RawSerializer(hEADER.GetType(), false);
            MemoryStream  target        = new MemoryStream(buffer);
            int           num;

            rawSerializer.Serialize(hEADER, target, out num);
        }
Beispiel #16
0
        public void sendMsg(string user, HEADER obj)
        {
            if (user == null || !mUserMap.ContainsKey(user))
            {
                return;
            }

            ICDPacketMgr.GetInst().sendMsgToClient(mUserMap[user], obj);
        }
Beispiel #17
0
        public static HEADER Deserialize(String filePath)
        {
            HEADER        rtn        = null;
            XmlSerializer serializer = new XmlSerializer(typeof(HEADER));
            StreamReader  reader     = new StreamReader(filePath);

            rtn = (HEADER)serializer.Deserialize(reader);
            reader.Close();
            return(rtn);
        }
Beispiel #18
0
            static public HEADER GetHeaderInfo(byte[] buf)
            {
                HEADER obj      = new HEADER();
                int    headSize = HeaderSize();

                byte[] headBuf = new byte[headSize];
                Array.Copy(buf, headBuf, headSize);
                Deserialize(obj, ref headBuf);
                return(obj);
            }
Beispiel #19
0
        private void RequestTaskList(DateTime from, DateTime to)
        {
            HEADER msg = new HEADER();

            msg.FillClientHeader(DEF.CMD_TaskBaseList);

            msg.ext1 = from.ToString("yyyy-MM-dd HH:mm:ss");
            msg.ext2 = to.ToString("yyyy-MM-dd HH:mm:ss");

            ICDPacketMgr.GetInst().sendMsgToServer(msg);
        }
Beispiel #20
0
            static public void HeadBuilder(object obj, COMMAND id, TYPE type)
            {
                HEADER head = obj as HEADER;

                head.id    = (uint)id;
                head.size  = (uint)Marshal.SizeOf(obj);
                head.sof   = (uint)MAGIC.SOF;
                head.type  = (uint)type;
                head.error = (uint)ERRORCODE.NOERROR;
                head.time  = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
            }
Beispiel #21
0
        public void set(int contID, int channel)
        {
            HEADER h = new HEADER();

            h.command     = (int)COMMANDS.cping;
            h.signum      = SIGNUM.BIN;
            h.containerID = contID;
            h.channelID   = channel;
            h.size        = network_utils.nData.Instance.getSize <ping>();
            header        = h;
        }
Beispiel #22
0
        private void ICD_ProcChat(int clientID, HEADER obj)
        {
            ChatRoomInfo msg = (ChatRoomInfo)obj;

            if (!mRooms.ContainsKey(msg.body.recordID))
            {
                LOG.warn();
                return;
            }

            mRooms[msg.body.recordID].ProcChat(msg);
        }
Beispiel #23
0
 public void FillHeader(HEADER head)
 {
     msgID   = head.msgID;
     msgSize = head.msgSize;
     msgSOF  = head.msgSOF;
     msgType = head.msgType;
     msgErr  = head.msgErr;
     msgUser = head.msgUser;
     msgTime = head.msgTime;
     ext1    = "";
     ext2    = "";
 }
Beispiel #24
0
    void Start()
    {
        currStage   = STAGE.BlackBG;
        headerStage = HEADER.MoveDown;
        scaleTimer  = 2.5f;
        fadeOut     = false;
        fadeToMenu  = false;

        playerIcon1.GetComponent <Image>().sprite = IconManager.Instance.GetIcon((Defines.ICONS)GlobalScript.Instance.iconP1);
        playerIcon2.GetComponent <Image>().sprite = IconManager.Instance.GetIcon((Defines.ICONS)GlobalScript.Instance.iconP2);
        playerName1.GetComponent <Text>().text    = GlobalScript.Instance.nameP1;
        playerName2.GetComponent <Text>().text    = GlobalScript.Instance.nameP2;
    }
Beispiel #25
0
 /// <summary>
 /// 헤더 값을 가진 빈 패킷을 생성합니다.
 /// 패킷에는 Int32, float, bool, string 데이터를 넣을 수 있으며, 최대 받을 수 있는 용량은 미리 정의된 세션마다 할당하는 버퍼의 최대 사이즈 입니다.
 /// capacity 만큼 버퍼를 할당하며, 버퍼를 초과 할때 마다 버퍼의 양을 두배로 늘려서 처리합니다. 또한 미리 정의된 세션당 버퍼 값을 넘어갈때에는 예외를 던집니다.
 /// </summary>
 /// <param name="head"></param>
 /// <param name="capacity"></param>
 public Packet(HEADER head, int capacity = 32)
 {
     if (capacity > Config.MAX_SESSION_BUFFER_SIZE)
     {
         throw new Exception("Packet pre-Allocate Memory over the max Session buffer size");
     }
     else
     {
         data = new byte[capacity];
     }
     SizeIncludedFixedArea = HEADER_SIZE + sizeof(Int32);
     Head = head;
 }
Beispiel #26
0
    public float GetProgressState()
    {
        int currentSize = mFifoBuffer.GetSize();

        if (currentSize < stHeader.HeaderSize())
        {
            return(1f);
        }

        HEADER head = new HEADER();

        byte[] headBuf = mFifoBuffer.readSize(stHeader.HeaderSize());
        Utils.Deserialize(ref head, headBuf);
        return(currentSize / (float)head.len);
    }
Beispiel #27
0
 private int RecvHeader(ref HEADER header)
 {
     try
     {
         byte[]        buffer        = new byte[5];
         int           result        = this._parent.Sock.Receive(buffer);
         RawSerializer rawSerializer = new RawSerializer(header.GetType(), false);
         MemoryStream  source        = new MemoryStream(buffer);
         rawSerializer.Deserialize <HEADER>(ref header, source);
         return(result);
     }
     catch (Exception)
     {
     }
     return(0);
 }
Beispiel #28
0
        private void OnProcTaskHistroy(int clientID, HEADER obj)
        {
            switch (obj.msgID)
            {
            case ICD.DEF.CMD_TaskBaseList:
                ProcTaskListTime(obj);
                break;

            case ICD.DEF.CMD_TaskHistory:
                ProcTaskHistory(obj);
                break;

            default:
                break;
            }
        }
Beispiel #29
0
            public HEADER Clone()
            {
                HEADER newObj = new HEADER();

                newObj.msgID   = msgID;
                newObj.msgSize = msgSize;
                newObj.msgSOF  = msgSOF;
                newObj.msgType = msgType;
                newObj.msgErr  = msgErr;
                newObj.msgUser = msgUser;
                newObj.msgTime = msgTime;
                newObj.ext1    = ext1;
                newObj.ext2    = ext2;

                return(newObj);
            }
Beispiel #30
0
        private void procData(NetworkMgr.QueuePack pack)
        {
            while (true)
            {
                long nRecvLen = pack.buf.GetSize();
                int  headSize = ICD.HEADER.HeaderSize();
                if (nRecvLen < headSize)
                {
                    break;
                }

                byte[] headBuf = pack.buf.readSize(headSize);
                HEADER head    = new HEADER();
                head.Deserialize(ref headBuf);
                if (head.msgSOF != ICD.DEF.MAGIC_SOF)
                {
                    pack.buf.Clear();
                    break;
                }

                int msgSize = head.msgSize;
                if (nRecvLen < msgSize)
                {
                    break;
                }

                byte[] msgBuf = pack.buf.Pop(msgSize);

                HEADER msg = null;
                if (head.msgType == DEF.TYPE_REQ)
                {
                    msg = CreateICD_onServer(head);
                }
                else if (head.msgType == DEF.TYPE_REP)
                {
                    msg = CreateICD_onClient(head);
                }
                else
                {
                    LOG.warn();
                }

                msg.Deserialize(ref msgBuf);
                OnRecv?.Invoke(pack.ClientID, msg);
            }
        }
Beispiel #31
0
	/// <summary>
	/// Retrieve object header from storage.
	/// </summary>
	/// <param name="header">In/Out header value.</param>
	public void Retrieve( ref HEADER header )
	{
		#region debug info
#if (DEBUG)
		Debug.Print( "-> ODB.Retrieve( {0}, {1} )", header.ID, header.Type );
#endif
		#endregion

		// open connection and start new transaction if required
		TransactionBegin();

		try {
			header = get_header( header.ID );
		} catch( Exception ex ) {
			#region debug info
#if (DEBUG)
			Debug.Print( "[ERROR] @ ODB.Retrieve: {0}", ex.ToString() );
#endif
			#endregion
			// rollback failed transaction
			TransactionRollback();
			throw;
		}
		// close connection and commit transaction if required
		TransactionCommit();
		#region debug info
#if (DEBUG)
		Debug.Print( "<- ODB.Retrieve( {0}, {1} )", header.ID, header.Type );
#endif
		#endregion
	}
Beispiel #32
0
	/// <summary>
	/// Delete object with specified header from storage.
	/// </summary>
	/// <param name="header">Header value.</param>
	public void Delete( HEADER header )
	{
		#region debug info
#if (DEBUG)
		Debug.Print( "-> ODB.Delete({0})", header.ID );
#endif
		#endregion

		// open connection and start new transaction if required
		TransactionBegin();
		try {
			// check object stamp. If it is newer then current -> raise error
			DbCommand cmd = new SqlCommand( string.Format(
				"DECLARE @_id AS int; SET @_id = @ID;\n" +
				"IF ((SELECT [TimeStamp] FROM [dbo].[_objects] WHERE [ID] = @_id) > @Stamp) " +
				"RAISERROR( '{0}', 11, 1 );",
				ERROR_CHANGED_OBJECT) );
			cmd.Connection = m_con;
			cmd.Transaction = m_trans;
			// add proxy stamp parameter
			cmd.Parameters.Add(new SqlParameter("@ID", header.ID));
			cmd.Parameters.Add(new SqlParameter("@Stamp", header.Stamp));

			cmd.CommandText += "DELETE FROM [dbo].[_objects] WHERE [ID] = @_id";

			// proccess delete opearaton
			cmd.ExecuteNonQuery();
		} catch( Exception ex ) {
			#region dubug info
#if (DEBUG)
			Debug.Print( "[ERROR] @ ODB.Delete: {0}", ex.ToString() );
#endif
			#endregion
			// rollback failed transaction
			TransactionRollback();
			throw;
		}
		// close connection and commit transaction if required
		TransactionCommit();
		#region debug info
#if (DEBUG)
		Debug.Print( "<- ODB.Delete({0})", header.ID );
#endif
		#endregion
	}
Beispiel #33
0
	/// <summary>
	/// Retrieve object header, links and properties.
	/// </summary>
	/// <param name="header">In/Out header value.</param>
	/// <param name="links">Array of object links.</param>
	/// <param name="props">Array of object properties.</param>
	public void Retrieve( ref HEADER header, out LINK[] links,
						  out PROPERTY[] props )
	{
		#region debug info
#if (DEBUG)
		Debug.Print( "-> ODB.Retrieve( {0}, {1} )", header.ID, header.Type );
#endif
		#endregion

		List<PROPERTY> _props = new List<PROPERTY>();	// list to store properties of object
		List<LINK> _links = new List<LINK>();	// list to store child proxy objects
		DbDataReader dr = null;
		DbCommand cmd = null;
		// init out parameters
		links = null;
		props = null;

		// open connection and start new transaction if required
		TransactionBegin();
		try {
			// get object header
			HEADER newHeader = get_header( header.ID );

			if( header.Stamp == newHeader.Stamp ) {
				header = newHeader;
				// close connection and commit transaction if required
				TransactionCommit();
				return;
			}

			#region retrive props from _properties
			cmd = new SqlCommand( string.Format(
					"SELECT [Name], [Value] FROM [dbo].[_properties] WHERE [ObjectID] = {0}",
					header.ID) );
			cmd.Connection = m_con;
			cmd.Transaction = m_trans;

			dr = cmd.ExecuteReader( CommandBehavior.SingleResult );
			try {
				// read all simple properties of object
				while( dr.Read() ) {
					// read properties from row
					string name = (string) dr["Name"];
					object val	= dr["Value"];

					// convert byte array to memory stream
					if( val.GetType() == typeof(Byte[] ) ) {
						val = new PersistentStream((Byte[])val );
					}
					// build PersistentProperty upon recieved name and value and
					// save property in collection
					_props.Add( new PROPERTY( name, new ValueBox(val), PROPERTY.STATE.New ));
				}
			} finally {
				// Dispose SqlDataReader
				dr.Dispose();
			}
			#endregion

			#region retrive props from _images
			cmd = new SqlCommand( string.Format(
				"SELECT [Name] FROM [dbo].[_images] WHERE [ObjectID] = {0}",
				header.ID) );
			cmd.Connection = m_con;
			cmd.Transaction = m_trans;

			SqlDataAdapter da = new SqlDataAdapter( (SqlCommand)cmd );
			DataTable dt = new DataTable(); // table for object proxy properties

			da.Fill( dt ); // fill table
			DataTableReader dtr = new DataTableReader(dt);
			try {
				while( dtr.Read() ) {
					// save data from SqlDataReader because we need non SequentialAccess in datarow
					string name = (string) dtr["Name"];
					// save property in collection
					_props.Add( new PROPERTY( name,
											  new ValueBox( read_blob( header.ID, name ) ),
											  PROPERTY.STATE.New ));
				}
			} finally {
				dtr.Dispose();
			}
			#endregion

			#region retrive links
			cmd = new SqlCommand( string.Format(
				"SELECT [ID], [ObjectName], [ObjectType], [TimeStamp]\n" +
				"FROM [dbo].[_objects]\n" +
				"WHERE [ID] IN (SELECT Child FROM [dbo].[_links] WHERE Parent = {0})",
				header.ID) );
			cmd.Connection = m_con;
			cmd.Transaction = m_trans;

			dr = cmd.ExecuteReader( CommandBehavior.SingleResult );
			try {
				while( dr.Read() ) {
					// save child header
					_links.Add( new LINK(
						new HEADER((string) dr["ObjectType"],
							Convert.ToInt32( dr["ID"] ),
							Convert.ToDateTime( dr["TimeStamp"] ),
							(string) dr["ObjectName"] ),
							LINK.STATE.New));
				}
			} finally { dr.Dispose(); }
			#endregion

			props = _props.ToArray();
			links = _links.ToArray();
			header = newHeader;
		} catch( Exception ex ) {
			#region debug info
#if (DEBUG)
			Debug.Print( "[ERROR] @ ODB.Retrive: {0}", ex.ToString() );
#endif
			#endregion
			// rollback failed transaction
			TransactionRollback();
			throw;
		}
		// close connection and commit transaction if required
		TransactionCommit();

		#region debug info
#if (DEBUG)
		Debug.Print( "<- ODB.Retrieve({0}, {1})", header.ID, header.Type );
#endif
		#endregion
	}
Beispiel #34
0
	/// <summary>
	/// Save object header, links and properties to storage.
	/// </summary>
	/// <param name="header">In/Out header value.</param>
	/// <param name="links">Array of modified object links.</param>
	/// <param name="props">Array of modified object properties.</param>
	/// <param name="mlinks">Array of new object links.</param>
	/// <param name="mprops">Array of new object properties.</param>
	public void Save( ref HEADER header, LINK[] links, PROPERTY[] props,
					  out LINK[] mlinks, out PROPERTY[] mprops )
	{
		#region debug info
#if (DEBUG)
		Debug.Print( "-> ODB.Save( {0}, {1}, {2}, {3}, {4} )",
					header.ID, header.Type, 
					header.Stamp, props.GetUpperBound( 0 ),
					links.GetUpperBound( 0 ) );
#endif
		#endregion

		DbCommand cmd = null;			// other puroses
		List<PROPERTY> _props = null;	// list for collecting current object properties
		int objID;						// object ID

		// initialize out parameters
		mlinks = null;
		mprops = null;

		// open connection and start new transaction if required
		TransactionBegin();
		try {
			#region create new object proxy if it is new or check it's stamp
			// assign command which will insert or (check, update) object record in DB
			if( header.ID == 0 ) {
				// this is new object. Creating script for insertion of object
				cmd =
					new SqlCommand(
						"\nINSERT INTO [dbo].[_objects] ( [ObjectName], [ObjectType] ) " +
						"VALUES ( @Name, @Type );\n" +
						/*save inserted object ID*/
						"SET @ID = SCOPE_IDENTITY();");
				cmd.Connection = m_con;
				cmd.Transaction = m_trans;
				// add proxy name parameter
				cmd.Parameters.Add(new SqlParameter("@Name", header.Name));
				// add proxy name parameter
				cmd.Parameters.Add(new SqlParameter("@Type", header.Type));
				// add proxy ID parameter
				cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int));
				cmd.Parameters["@ID"].Direction = ParameterDirection.Output;
			} else {
				// check object stamp. If it is newer then current -> raise error
				cmd = new SqlCommand( string.Format(
					"DECLARE @_id AS Int; SET @_id = @ID;\n" +
					"IF ((SELECT [TimeStamp] FROM [dbo].[_objects] WHERE [ID] = @_id) > @Stamp) " +
					"RAISERROR( '{0}', 11, 1 );",
					ERROR_CHANGED_OBJECT ) );
				cmd.Connection = m_con;
				cmd.Transaction = m_trans;
				// add proxy ID parameter
				cmd.Parameters.Add(new SqlParameter("@ID", header.ID));
				// add proxy stamp parameter
				cmd.Parameters.Add( new SqlParameter("@Stamp", header.Stamp));
				// proxy name is always updated
				cmd.CommandText += "UPDATE [dbo].[_objects] SET [ObjectName] = @Name WHERE [ID] = @_id";

				// add proxy name parameter
				cmd.Parameters.Add( new SqlParameter( "@Name", header.Name) );
			}

			// execute batch
			cmd.ExecuteNonQuery();
			// get proxy ID returned by batch execution
			objID = Convert.ToInt32( cmd.Parameters["@ID"].Value );
			#endregion

			// create new command
			cmd = new SqlCommand("");
			cmd.Connection = m_con;
			cmd.Transaction = m_trans;
			_props = new List<PROPERTY>();

			// iterate through received properties
			for( int i = 0; i < props.Length; i++ ) {
				// check for property state and type for different processing
				if( props[i].State == PROPERTY.STATE.Deleted ) {
					// just delete property from _properties/_images table
					cmd.CommandText += string.Format(
						"DELETE FROM [dbo].[_properties] WHERE [ObjectID] = {0} AND [Name] = '{1}'; \n" +
						"IF @@ROWCOUNT = 0 BEGIN                                                    \n" + 
						"    DELETE FROM [dbo].[_images] WHERE [ObjectID] = {0} AND [Name] = '{1}'; \n" +
						"END;                                                                       \n",
						objID, props[i].Name );
				} else if( props[i].Value.ToObject() is PersistentStream &&
						   (props[i].Value.ToObject() as PersistentStream).Length > 7900 ) {
					// save large stream property: 7900 is maximum length of sql_variant field in
					// _properties table because SQL Server limits maximum row size to 8060 bytes,
					// so save stream property as blob
					save_blob( objID, props[i].Name, (PersistentStream)props[i].Value,
							   props[i].State == PROPERTY.STATE.New );
				} else {
					// convert property value to sql_variant capable type
					object value;
					if( props[i].Value.ToObject() is PersistentStream ) {
						// this is a little stream, so convert stream value to byte array
						PersistentStream s = props[i].Value.ToObject() as PersistentStream;
						byte[] buffer = new byte[s.Length];
						s.Seek( 0, SeekOrigin.Begin );
						s.Read( buffer, 0, (int)s.Length );
						value = buffer;
					} else if( props[i].Value.ToObject().GetType() == typeof(DateTime) ) {
						// DateTime property must be converted to precision of sql server before save
						value = datetime_to_sql( (DateTime)props[i].Value );
						// add to changed properies list to return to client
						_props.Add( new PROPERTY(props[i].Name, new ValueBox(value), PROPERTY.STATE.Changed) );
					} else {
						// no convertion is needed
						value = props[i].Value.ToObject();
					}

					// compose sql command to update/insert data into _properties table
					if( props[i].State == PROPERTY.STATE.Changed ) {
						// compose UPDATE command (if this is binary property change, add
						// some extra processing: _images can contain this property already)
						cmd.CommandText += string.Format(
							"UPDATE [dbo].[_properties] SET [Value] = @P{2} WHERE [ObjectID] = {0} AND [Name] = '{1}';     \n" +
							(!(props[i].Value.ToObject() is PersistentStream) ? "" :
							"IF @@ROWCOUNT = 0 BEGIN                                                                       \n" +
							"    DELETE FROM [dbo].[_images] WHERE [ObjectID] = {0} AND [Name] = '{1}';                    \n" +
							"    INSERT INTO [dbo].[_properties] ([ObjectID], [Name], [Value]) VALUES ({0}, '{1}', @P{2}); \n" +
							"END;                                                                                          \n"),
							objID, props[i].Name, i );
					} else {
						// compose INSERT command
						cmd.CommandText += string.Format(
							"INSERT INTO [dbo].[_properties] ([ObjectID], [Name], [Value]) VALUES ({0}, '{1}', @P{2}); \n",
							objID, props[i].Name, i );
					}
					cmd.Parameters.Add( new SqlParameter( "@P" + i, value ) );
				}
			}

			// iteration throught links
			foreach( LINK link in links ) {
				// check link action
				if( link.State == LINK.STATE.New ) {
					// add new link to DB
					cmd.CommandText += string.Format(
						"INSERT INTO [dbo].[_links] ([Parent], [Child]) VALUES ({0}, {1}); \n",
						objID, link.Header.ID );
				} else if( link.State == LINK.STATE.Deleted ) {
					// delete link from DB
					cmd.CommandText += string.Format(
						"DELETE FROM [dbo].[_links] WHERE [Parent] = {0} AND [Child] = {1}; \n",
						objID, link.Header.ID );
				}
			}

			// executing batch
			if( cmd.CommandText != "" ) cmd.ExecuteNonQuery();

			// return proxy properties
			header = get_header( objID );
			// and changed properies if exists
			if( _props.Count > 0 )
				mprops = _props.ToArray();
		} catch( Exception ex ) {
			#region debug info
#if (DEBUG)
			Debug.Print( "[ERROR] @ ODB.Save: {0}", ex.ToString() );
#endif
			#endregion
			// rollback failed transaction
			TransactionRollback();
			throw;
		}
		// close connection and commit transaction if required
		TransactionCommit();

		#region debug info
#if (DEBUG)
		Debug.Print( "<- ODB.Save(ID:{0}, Type:'{1}', Name:'{2}', Stamp:'{3}' )",
					header.ID, header.Type, header.Name, header.Stamp );
#endif
		#endregion
	}
Beispiel #35
0
	/// <summary>
	/// Search objects that sutisfies search criteria.
	/// </summary>
	/// <param name="type">Objects type.</param>
	/// <param name="where">Where object</param>
	/// <param name="order">>OrderBy object</param>
	/// <param name="bottom">Bottom limit in the request.</param>
	/// <param name="count">Count limit in the request.</param>
	/// <param name="headers">Array of found object headers.</param>
	/// <returns>Count of found objects</returns>
	public int Search(string type, Where where, OrderBy order, int bottom, int count, out HEADER[] headers)
	{
		#region debug info
#if (DEBUG)
		Debug.Print("-> ODB.Search( '{0}')", type );
#endif
		#endregion
		// init search command
		using( DbCommand cmd = new SqlCommand() ) {
			// list for HEADERs return purpose
			List<HEADER> objects = null;

			// for SqlParameter names and values
			Dictionary<string, object> parms = new Dictionary<string, object>();
			// create sql command text
			string whereQuery = "";
			if( where != null ) {
				whereQuery = where_to_cmd(where, parms);
			}

			#region prepare OrderBy part
			string orderJoin = "";
			string orderBy = "";

			if( order != null ) {
				foreach( OrderBy.Clause clause in order ) {
					string orderJoinOut;
					string orderByOut;
					orderby_to_cmd(clause, out orderJoinOut, out orderByOut);
					orderJoin += orderJoinOut;
					orderBy += orderByOut + ", ";
				}
				orderBy = orderBy.Trim().TrimEnd(',');
			}
			#endregion

			// template for search query:
			// - gets ids of object that meets {0},
			// - skips @bottom rows
			// - return only @count object HEADERs
			cmd.CommandText="DECLARE @_i as int\n" +
							"DECLARE @_id as int\n" +
							"DECLARE @_ids TABLE ([id] int)\n" +
							"--return requested count of items\n" +
							"DECLARE curs CURSOR LOCAL STATIC READ_ONLY FOR\n" +
							"{0}\n" +
							"OPEN curs\n" +
							"    SET @found = @@CURSOR_ROWS\n" +
							"    SET @_i = 0\n" +
							"    FETCH ABSOLUTE @bottom FROM curs INTO @_id\n" +
							"    WHILE( @@FETCH_STATUS = 0 AND @_i < @count ) BEGIN\n" +
							"        INSERT INTO @_ids ([id]) VALUES (@_id)\n" +
							"        FETCH NEXT FROM curs INTO @_id\n" +
							"        SET @_i = @_i + 1\n" +
							"    END\n" +
							"CLOSE curs\n" +
							"DEALLOCATE curs\n" +
							"--Make SQL request\n" +
							"SELECT [o].[ID], [o].[ObjectName], [o].[ObjectType], [o].[TimeStamp]\n" +
							"FROM [dbo].[_objects] [o] INNER JOIN @_ids AS [ids] ON [o].[ID] = [ids].[id]";

			// search query part with ordering
			string query = string.Format(
							"SELECT [src].[ID]\n" +
							"FROM (SELECT * FROM [dbo].[_objects] WHERE [ObjectType] = '{0}') AS [src]" + 
							"{1}\n" + //orderJoin
							"{2}\n" + //WHERE
							"{3}", // ORDER BY
							type, orderJoin,
							string.IsNullOrEmpty(whereQuery) ? "" : "WHERE " + whereQuery,
							orderBy == "" ? "" : "ORDER BY " + orderBy );
			SqlParameter param = new SqlParameter( "@found", SqlDbType.Int );
			param.Direction = ParameterDirection.Output;
			cmd.Parameters.Add( param );
			// setting query count limits
			cmd.Parameters.Add( new SqlParameter( "@bottom", bottom + 1 ) );
			cmd.Parameters.Add( new SqlParameter( "@count", count ) );
			// creating SqlParameters for passed values
			foreach( string parm in parms.Keys ) {
				cmd.Parameters.Add( new SqlParameter(parm, parms[parm]));
			}
			// replacing parts in search query template
			cmd.CommandText = string.Format( cmd.CommandText, query );
	#if (DEBUG)
			Debug.Print("ODB.Search: sql search query = '{0}'", cmd.CommandText );
	#endif

			// open connection and start new transaction if required
			TransactionBegin();
			try {
				cmd.Connection = m_con;
				cmd.Transaction = m_trans;
				// search query will return table with the following columns:
				// ID, ObjectName, ObjectType, TimeStamp
				#region retrive data and create proxies
				DbDataReader dr = cmd.ExecuteReader();
				// create List for storing found objects
				objects = new List<HEADER>();
				try {
					while( dr.Read() ) {
						// save found proxy object
						objects.Add(new HEADER((string)dr["ObjectType"],
												Convert.ToInt32(dr["ID"]),
												Convert.ToDateTime(dr["TimeStamp"]),
												(string)dr["ObjectName"]));
					}
				} finally { dr.Dispose(); }
				#endregion
			} catch( Exception ex ) {
				#region debug info
	#if (DEBUG)
				Debug.Print("[ERROR] @ ODB.Search: {0}", ex.ToString());
	#endif
				#endregion
				// rollback failed transaction
				TransactionRollback();
				throw;
			}
			// close connection and commit transaction if required
			TransactionCommit();

			// return objects found
			headers = objects.ToArray();
			#region debug info
	#if (DEBUG)
			Debug.Print("<- ODB.Search( '{0}', '{1}') = {2}", type, where, objects.Count);
	#endif
			#endregion
			// return count objects found
			return (int)cmd.Parameters["@found"].Value;
		}
	}