예제 #1
0
        private void threadStartFun(Socket soc, string req)
        {
            try
            {
                Program.ServerForm.addtoConsole("Service Poll Req Thread Started");
                Server.Message.MessageParser serverPollPar = new Server.Message.MessageParser();
                Server.MessageClasses.MsgPoll msgpollServer = serverPollPar.pollParseMsg(req);

                CloudBlobClient blobClient = new Server.ConnectionManager.BlobConn().BlobConnect();
                Blob blob = new Blob(blobClient, msgpollServer.userName);
                GenerateSAS sas = new GenerateSAS();
                string link = "";
                if (msgpollServer.password == "requestVC")
                {
                    link = sas.GetContainerSasUri(blob.container, "RWLD");
                }
                else
                {
                    link = sas.GetContainerSasUri(blob.container, "RWLD");
                }

                // Server send response to Client
                Server.Message.CreateMsg pollResp = new Server.Message.CreateMsg();
                msgpollServer.fileContainerUri = link;
                msgpollServer.fileBlobUri = "none";
                string respMsg = pollResp.pollRespMsg("OK", msgpollServer);

                //socket
                SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                // write to socket
                rw.writetoSocket(soc, respMsg);
                Program.ServerForm.addtoConsole("Wrote Response to socket");

            }
            catch (Exception e)
            {
                Program.ServerForm.addtoConsole("Exception: [Poll Req]"+ e.Message);
                //System.Windows.Forms.MessageBox.Show(e.ToString());
            }
            finally
            {
                Program.ServerForm.addtoConsole("Exiting");
                Thread.CurrentThread.Abort();
            }
        }
예제 #2
0
파일: VCThread.cs 프로젝트: hangmiao/DBLike
        private void threadStartFun()
        {
            try
            {
                Console.WriteLine("in Vc thread");
                // Client create poll msg
                LocalDB readLocalDB = new LocalDB();
                readLocalDB = readLocalDB.readfromfile();
                Client.MessageClasses.MsgPoll msgpoll = new Client.MessageClasses.MsgPoll();
                Client.Message.CreateMsg pollM = new Client.Message.CreateMsg();
                msgpoll.userName = readLocalDB.getUsername();
                msgpoll.password = "******";
                string msg = pollM.pollMsg(msgpoll);

                //send the msg using socket
                ConnectionManager.Connection conn = new ConnectionManager.Connection();
                Socket soc = conn.connect(conf.serverAddr, conf.port);

                SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                rw.writetoSocket(soc, msg);

                //receive the msg
                string resp = rw.readfromSocket(soc);

                //parse msg and poll
                Client.Message.MessageParser parseResp = new Client.Message.MessageParser();
                msgpoll = parseResp.pollParseMsg(resp);
                if (msgpoll.indicator == "OK")
                {
                    Configuration.userInfo.containerURI = msgpoll.fileContainerUri;
                    // write container somewhere (msgpoll.fileContainerUri);
                }

            }
            catch (Exception e)
            {
                Program.ClientForm.addtoConsole(e.ToString());
                System.Windows.Forms.MessageBox.Show(e.ToString());
                //System.IO.File.WriteAllText("errors.txt", e.ToString());
            }
            finally
            {
                Thread.CurrentThread.Abort();
            }
        }
예제 #3
0
        public void poll()
        {
            Configuration.flag.polling = true;
            Program.ClientForm.addtoConsole("Poll initiated");

            //MessageBox.Show("Polling started", "Client");
            try
            {
                // Client create poll msg
                LocalDB readLocalDB = new LocalDB();
                readLocalDB = readLocalDB.readfromfile();

                Client.MessageClasses.MsgPoll msgpoll = new Client.MessageClasses.MsgPoll();
                Client.Message.CreateMsg pollM = new Client.Message.CreateMsg();
                msgpoll.userName = readLocalDB.getUsername();
                msgpoll.password = readLocalDB.getPassword();
                string msg = pollM.pollMsg(msgpoll);

                //send the msg using socket
                ConnectionManager.Connection conn = new ConnectionManager.Connection();
                Socket soc = conn.connect(conf.serverAddr, conf.port);

                SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                rw.writetoSocket(soc, msg);
                Program.ClientForm.addtoConsole("Writing Socket");
                //receive the msg
                string resp = rw.readfromSocket(soc);
                Program.ClientForm.addtoConsole("Reading Socket");
                //parse msg and poll
                Client.Message.MessageParser parseResp = new Client.Message.MessageParser();
                msgpoll = parseResp.pollParseMsg(resp);
                if (msgpoll.indicator == "OK")
                {
                    new Client.PollFunction.Poll(msgpoll.fileContainerUri);
                    Configuration.userInfo.containerURI = msgpoll.fileContainerUri;
                }
                Configuration.flag.polling = false;
            }
            catch(Exception ex)
            {
                Program.ClientForm.addtoConsole("Poll thread Exception:" + ex.Message);
                //System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
        }
예제 #4
0
        private void threadStartFun(Socket soc, string req)
        {
            Program.ServerForm.addtoConsole("Sign In thread Started");
            Message.MessageParser parser = new Message.MessageParser();
            MessageClasses.MsgSignIn.req reqobj = new MessageClasses.MsgSignIn.req();
            reqobj = parser.signInParseReq(req);
            ConnectionManager.DataBaseConn con = new ConnectionManager.DataBaseConn(1);
            SqlConnection conn = con.DBConnect();
            //check if user already exits
            UserAuth.SignInFunctions userauth = new UserAuth.SignInFunctions();
            if(userauth.userAuthentication(reqobj.userName,reqobj.psw)==true)
            {
                Program.ServerForm.addtoConsole("User Exists");
                MessageClasses.MsgSignIn.resp resp = new MessageClasses.MsgSignIn.resp();
                resp.ack = "OK";
                resp.addiMsg = "EXISTING";
                Message.CreateMsg msg = new Message.CreateMsg();
                string res = msg.signInResp(resp);
                SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                rw.writetoSocket(soc, res);
                Program.ServerForm.addtoConsole("Wrote Respose to scoket");
            }
            else
            {
                Program.ServerForm.addtoConsole("User Does Not Exist");
                MessageClasses.MsgSignIn.resp resp = new MessageClasses.MsgSignIn.resp();
                resp.ack = "ERRORS";
                resp.addiMsg = "NON-EXISTING";
                Message.CreateMsg msg = new Message.CreateMsg();
                string res = msg.signInResp(resp);
                SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                rw.writetoSocket(soc, res);
                Program.ServerForm.addtoConsole("Wrote Response to socket. Exiting");

            }
            Thread.CurrentThread.Abort();
        }
예제 #5
0
파일: Uploader.cs 프로젝트: hangmiao/DBLike
        private static void threadStartFun(string fullpathOfChnagedFile, string eventType, string addiInfo, DateTime timestamp)
        {
            try
            {

                Program.ClientForm.addtoConsole("Upload thread Started");
                //System.Windows.Forms.MessageBox.Show("Started Uploader for " + fullpathOfChnagedFile, "Client");
                //TBD
                //send msg to server
                //get the information from the localDatabase
                LocalDB readLocalDB = new LocalDB();
                readLocalDB = readLocalDB.readfromfile();

                string clientSyncFolderPath = readLocalDB.getPath();
                string[] pathName = clientSyncFolderPath.Split('\\');

                string[] pathName2 = fullpathOfChnagedFile.Split('\\');
                int i = pathName2.Count();
                string pathInSyncFolderPath = "";
                for (int j = pathName.Count(); j < i; j++)
                {
                    pathInSyncFolderPath += pathName2[j];
                    if ((j + 1) < i)
                    {
                        pathInSyncFolderPath += "\\";
                    }
                }
                string userName = readLocalDB.getUsername();
                string password = readLocalDB.getPassword();

                Client.Message.CreateMsg uploadM = new Client.Message.CreateMsg();
                string additionalInfo = "";

                if (eventType == "create" || eventType == "change" || eventType == "signUpStart")
                {
                    if (eventType == "create")
                    {
                        additionalInfo = "create";
                        // add to the file list
                        Client.LocalFileSysAccess.FileListMaintain addToFileList = new Client.LocalFileSysAccess.FileListMaintain();
                        addToFileList.addSingleFileToFileList(fullpathOfChnagedFile);
                    }
                    if (eventType == "change")
                    {
                        additionalInfo = "change";
                    }
                    if (eventType == "signUpStart")
                    {
                        additionalInfo = "signUpStart";
                    }

                    Program.ClientForm.addtoConsole("Event handling:" + eventType);
                    // get the initial attribute before making this "change"
                    Client.LocalFileSysAccess.FileInfo tmp = new Client.LocalFileSysAccess.FileInfo();
                    Client.LocalFileSysAccess.FileList.fileInfoDic.TryGetValue(fullpathOfChnagedFile, out tmp);
                    DateTime timeBefore = tmp.time;
                    string md5rBefore = tmp.md5r;

                    // belong to these events because for delete event it won't get the attributes anymore
                    Client.LocalFileSysAccess.getFileAttributes att = new Client.LocalFileSysAccess.getFileAttributes(fullpathOfChnagedFile);
                    DateTime time = att.lastModified.ToUniversalTime();
                    string msg;
                    string md5r = att.md5Value;

                    // create the msg

                    msg = uploadM.uploadMsg(userName, password, pathInSyncFolderPath, time, md5r, additionalInfo);

                    //send the msg using socket
                    ConnectionManager.Connection conn = new ConnectionManager.Connection();
                    Socket soc = conn.connect(conf.serverAddr, conf.port);

                    SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                    rw.writetoSocket(soc, msg);
                    Program.ClientForm.addtoConsole("Wrote to socket");
                    //receive the msg
                    string resp = rw.readfromSocket(soc);
                    Program.ClientForm.addtoConsole("Read from socket");
                    //8 Client parse msg
                    Client.Message.MessageParser par2 = new Client.Message.MessageParser();
                    if (resp != null)
                    {
                        Client.MessageClasses.MsgRespUpload reup = par2.uploadParseMsg(resp);

                        //9 Client upload
                        if (reup.indicator == "OK")
                        {
                            // event type when there's no file conflict
                            string tempEType = reup.addiInfo;

                            string[] str = null;
                            // get current file info on server
                            string[] separators = { "|||" };
                            // when event type is change
                            // otherwise directly upload, don't need to check conflict
                            if (reup.addiInfo.Contains("|||"))
                            {
                                str = reup.addiInfo.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                                string currHashValueOnServer = str[0];
                                string tempTimestampOnServer = str[1];
                                // reassign event type
                                tempEType = str[2];

                                //CultureInfo provider = new CultureInfo("en-US");
                                //CultureInfo provider = CultureInfo.InvariantCulture;
                                //tempTimestampOnServer = tempTimestampOnServer.Replace("-", "/");
                                Program.ClientForm.addtoConsole(tempTimestampOnServer);
                                DateTime currTimestampOnServer = DateTime.Parse(tempTimestampOnServer);
                                //DateTime currTimestampOnServer = DateTime.ParseExact(tempTimestampOnServer, "MM/dd/yyyy HH:mm:ss", null);

                                // file has been changed during open time and save time
                                // aka there's a newer version of this file uploaded by another user during this time
                                if (DateTime.Compare(timeBefore, currTimestampOnServer) < 0 && String.Compare(md5rBefore, currHashValueOnServer) != 0)
                                {
                                    string tMsg = "simultaneous editing confilct";
                                    string cMsg = "\nA newer version has been detected on the server.\nDo you want to save current version?\n\nYes to Save current file in another name\nNo to Download the newest version file from server";
                                    DialogResult dialogResult = MessageBox.Show(string.Format("{0}" + cMsg, fullpathOfChnagedFile), tMsg, MessageBoxButtons.YesNo);
                                    if (dialogResult == DialogResult.Yes)
                                    {

                                        string sourcePath = fullpathOfChnagedFile;
                                        string targetPath = "";

                                        // add time to new name
                                        string dateString = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
                                        //string dateString = DateTime.UtcNow.ToString("MM/dd/yyyy HH:mm:ss");
                                        string[] fileNameArr = sourcePath.Split('.');
                                        string newFileName = fileNameArr[0] + " ( " + Environment.UserName + "'s conflict copy " + dateString + ")." + fileNameArr[1];
                                        targetPath = newFileName;

                                        //// To copy a folder's contents to a new location:
                                        //// Create a new target folder, if necessary.
                                        //if (!System.IO.Directory.Exists(targetPath))
                                        //{
                                        //    System.IO.Directory.CreateDirectory(targetPath);
                                        //}

                                        // To copy a file to another location and
                                        // overwrite the destination file if it already exists.
                                        System.IO.File.Copy(sourcePath, targetPath, true);

                                    }
                                    else if (dialogResult == DialogResult.No)
                                    {

                                        // try delete while it still exists
                                        while (System.IO.File.Exists(fullpathOfChnagedFile))
                                        {
                                            // delete current file
                                            // won't delete blob file on the server
                                            // b/c it's older than that version
                                            System.IO.File.Delete(fullpathOfChnagedFile);

                                        }

                                        // if file is in dic
                                        if (Client.LocalFileSysAccess.FileList.fileInfoDic.ContainsKey(fullpathOfChnagedFile))
                                        {
                                            // after it has been deleted
                                            // del from the file list
                                            Client.LocalFileSysAccess.FileListMaintain delFromFileList = new Client.LocalFileSysAccess.FileListMaintain();
                                            delFromFileList.removeSingleFileFromFileList(fullpathOfChnagedFile, time, md5r);

                                            // TODO
                                            // download newer version from server

                                        }
                                    }
                                }

                            }

                            new Client.UploadFunctions.UploadFile().UploadFileWithContainerUri(reup.fileContainerUri, fullpathOfChnagedFile, reup.filePathInSynFolder, md5r, time, eventType);
                            //System.Windows.Forms.MessageBox.Show(string.Format("Uploaded! \n event type: {0} \n Path: {1}", tempEType, fullpathOfChnagedFile), "DBLike Client");
                            Program.ClientForm.addtoConsole(string.Format("Uploaded! \n event type: {0} \n Path: {1}", tempEType, fullpathOfChnagedFile));
                            // update file list
                            Client.LocalFileSysAccess.FileListMaintain updateFileList = new Client.LocalFileSysAccess.FileListMaintain();
                            updateFileList.updateSingleFileToFileList(fullpathOfChnagedFile, time, md5r);

                        }
                        //// handle simultaneous editing confilct
                        //// currently client will handle this
                        //if (reup.indicator == "simultaneousEditConfilct")
                        //{
                        //}

                    }
                    else
                    {
                        Program.ClientForm.addtoConsole("Error : <<Response from server is null>>");
                    }
                }

                else if (eventType == "delete")
                {
                    Program.ClientForm.addtoConsole("Event handling:" + eventType);
                    additionalInfo = "delete";
                    string msg = " ";
                    //System.Windows.Forms.MessageBox.Show(string.Format("Deletion detected!\n Path: {0}", pathInSyncFolderPath), "DBLike Client");

                    // file list maintainence_1
                    // delete the file from the file list
                    // grab it first by key, then delete
                    Client.LocalFileSysAccess.FileListMaintain reFileList = new Client.LocalFileSysAccess.FileListMaintain();
                    // get value by key
                    Client.LocalFileSysAccess.FileInfo tmpFInfo = new Client.LocalFileSysAccess.FileInfo();
                    Client.LocalFileSysAccess.FileList.fileInfoDic.TryGetValue(fullpathOfChnagedFile, out tmpFInfo);

                    // create the msg
                    // use " " instead of null to avoid parsing issue
                    // use DateTime.MinValue to avoid parsing issue
                    //msg = uploadM.uploadMsg(userName, password, pathInSyncFolderPath, DateTime.MinValue, " ", additionalInfo);
                    msg = uploadM.uploadMsg(userName, password, pathInSyncFolderPath, tmpFInfo.time, " ", additionalInfo);

                    //send the msg using socket
                    ConnectionManager.Connection conn = new ConnectionManager.Connection();
                    Socket soc = conn.connect(conf.serverAddr, conf.port);

                    SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                    rw.writetoSocket(soc, msg);

                    // file list maintainence_2
                    // remove file from file list
                    reFileList.removeSingleFileFromFileList(fullpathOfChnagedFile, tmpFInfo.time, tmpFInfo.md5r);
                    Program.ClientForm.ballon("Deleted:"+ fullpathOfChnagedFile);

                }
                else if (eventType == "rename")
                {
                    Program.ClientForm.addtoConsole("Event handling:" + eventType);
                    string[] separators = { "<", ">:<", ">" };
                    string[] reNameInfo = addiInfo.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    //List<string> temp = reNameInfo.ToList();
                    //temp.Insert(0, "rename");

                    //System.Windows.Forms.MessageBox.Show(string.Format("Rename detected!\n + Old Path: {0} \n + New Path: {1}", reNameInfo[0], reNameInfo[1]), "DBLike Client");

                    // get new path in server
                    string[] pathName3 = reNameInfo[1].Split('\\');
                    int m = pathName3.Count();
                    string newPathInSyncFolderPath = "";
                    for (int n = pathName.Count(); n < m; n++)
                    {
                        newPathInSyncFolderPath += pathName3[n];
                        if ((n + 1) < m)
                        {
                            newPathInSyncFolderPath += "\\";
                        }
                    }

                    // send event type and new path to server
                    additionalInfo = "rename" + "|||" + newPathInSyncFolderPath;

                    // only change last modified time to current time
                    // Windows 8 won't change last modified time when only renaming
                    Client.LocalFileSysAccess.getFileAttributes att = new Client.LocalFileSysAccess.getFileAttributes(reNameInfo[1]);
                    DateTime renameTime = DateTime.UtcNow;

                    string msg;
                    string md5r = att.md5Value;

                    // update the renamed file to the file list
                    Client.LocalFileSysAccess.FileListMaintain renameFileList = new Client.LocalFileSysAccess.FileListMaintain();

                    // get value by key
                    Client.LocalFileSysAccess.FileInfo tmpFI = new Client.LocalFileSysAccess.FileInfo();
                    Client.LocalFileSysAccess.FileList.fileInfoDic.TryGetValue(fullpathOfChnagedFile, out tmpFI);

                    // remove older file from file list
                    renameFileList.removeSingleFileFromFileList(fullpathOfChnagedFile, tmpFI.time, tmpFI.md5r);
                    // add new name file to file list
                    renameFileList.addSingleFileToFileList(reNameInfo[1]);

                    // create the msg
                    // pathInSyncFolderPath is the older path in server
                    // renameTime is the newest time
                    msg = uploadM.uploadMsg(userName, password, pathInSyncFolderPath, renameTime, md5r, additionalInfo);

                    //send the msg using socket
                    ConnectionManager.Connection conn = new ConnectionManager.Connection();
                    Socket soc = conn.connect(conf.serverAddr, conf.port);

                    SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                    rw.writetoSocket(soc, msg);

                    //receive the msg
                    //string resp = rw.readfromSocket(soc);

                    Program.ClientForm.ballon("Rename:" + fullpathOfChnagedFile);

                }

            }
            catch (Exception ex)
            {
                if (eventType != "delete")
                {
                    fileBeingUsed.eventDetails e = new fileBeingUsed.eventDetails();
                    e.eventType = eventType;
                    e.datetime = timestamp;
                    e.filepath = fullpathOfChnagedFile;
                    Client.Program.filesInUse.removefromList(e);

                }
                Program.ClientForm.addtoConsole("Exception Occured:" + ex.ToString());
                //System.Windows.Forms.MessageBox.Show(ex.ToString(), "Client");
                //System.IO.File.WriteAllText("errors.txt", e.ToString());
            }
            finally
            {
                if (eventType != "delete")
                {
                    fileBeingUsed.eventDetails e = new fileBeingUsed.eventDetails();
                    e.eventType = eventType;
                    e.datetime = timestamp;
                    e.filepath = fullpathOfChnagedFile;
                    Client.Program.filesInUse.removefromList(e);
                }
                Program.ClientForm.addtoConsole("Exiting");
                Thread.CurrentThread.Abort();
            }
        }
예제 #6
0
        private void threadStartFun(Socket soc, string req)
        {
            try
            {
                Program.ServerForm.addtoConsole("Service Upload thread Started");
                //System.Windows.Forms.MessageBox.Show("uploader started:" + req, "Server");
                //get the msg parse it
                Server.Message.MessageParser parse = new Server.Message.MessageParser();
                MessageClasses.MsgUpload upload = parse.uploadParseMsg(req);

                //5 Server check the file info in the blob storage, if file has not existed, let the client to create the file
                //  If file existed, check timestamp, hashvalue to see if client can upload
                //  If allow upload, change hashvalue and timestamp in the blob storage
                CloudBlobClient blobClient = new Server.ConnectionManager.BlobConn().BlobConnect();

                string currentFileInfo = "";

                if (upload.addInfo == "create" || upload.addInfo == "change" || upload.addInfo == "signUpStart")
                {
                    Program.ServerForm.addtoConsole("Event to trigger the request:" + upload.addInfo);
                    Blob blob = new Blob(blobClient, upload.userName, upload.filePathInSynFolder, upload.fileHashValue, upload.fileTimeStamps);

                    //6 Server Generate sas container/blob for the client. For basic upload, this case just generate container sas
                    //Server.ConnectionManager.BlobConn conn = new Server.ConnectionManager.BlobConn(1);

                    CloudBlobContainer container = blob.container;
                    string containerSAS = new Server.ConnectionManager.GenerateSAS().GetContainerSasUri(container, "RWLD");
                    Console.WriteLine("container sas uri: {0}", containerSAS);
                    Program.ServerForm.addtoConsole("SAS uri created");

                    //7 send upload msg back to client
                    Server.Message.CreateMsg resp = new Server.Message.CreateMsg();

                    currentFileInfo = upload.addInfo;

                    // when event type is change
                    // get current file info of the blob

                    CloudBlockBlob currBlob = container.GetBlockBlobReference(upload.filePathInSynFolder);
                    // when event type is change
                    // otherwise do nothing
                    if (currBlob.Exists())
                    {
                        currBlob.FetchAttributes();
                        string currHashValue = currBlob.Metadata["hashValue"];
                        //DateTime currTimestamp = DateTime.ParseExact(currBlob.Metadata["timestamp"], "MM/dd/yyyy HH:mm:ss",
                        //                                null); ;
                        //currTimestamp.ToString();
                        string currTimestamp = currBlob.Metadata["timestamp"];
                        currentFileInfo = currHashValue + "|||" + currTimestamp + "|||" + "change";
                        //blob.indicator = "OK";
                    }

                    //string respMsg = resp.uploadRespMsg(upload.filePathInSynFolder, containerSAS, null, upload.addInfo);
                    string respMsg = resp.uploadRespMsg(blob.indicator, upload.filePathInSynFolder, containerSAS, " ", currentFileInfo);

                    SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                    // write to socket
                    rw.writetoSocket(soc, respMsg);
                    //System.Windows.Forms.MessageBox.Show("uploader write:" + respMsg, "Server");
                    Program.ServerForm.addtoConsole("Wrote response to scoket");

                }

                if (upload.addInfo == "delete")
                {
                    // get container
                    CloudBlobContainer container = blobClient.GetContainerReference(upload.userName);
                    CloudBlockBlob delBlob = container.GetBlockBlobReference(upload.filePathInSynFolder);

                    // change value of delete in metadata to true
                    //container.Metadata["Deleted"] = "true";

                    if (delBlob.Exists())
                    {
                        // get to be deleted blob's info
                        delBlob.FetchAttributes();
                        string delHashValue = delBlob.Metadata["hashValue"];
                        //delHashValue =delHashValue.Replace("-", "/");
                        //DateTime delTimestamp = DateTime.ParseExact(delBlob.Metadata["timestamp"], "MM/dd/yyyy HH:mm:ss", null);
                        DateTime delTimestamp = DateTime.Parse(delBlob.Metadata["timestamp"]);

                        // only delete it when client's version is newer
                        // otherwise client's file is stale, don't delete server's blob
                        // b/c when simultaneous editing, client chooses to delete local copy
                        // it'll delete the server copy too!
                        if (DateTime.Compare(upload.fileTimeStamps, delTimestamp) >= 0)
                        {

                            //*** <<disabling deletion>>
                            UploadFunctions.DeleteFile del = new UploadFunctions.DeleteFile();
                            del.deleteAll(container, upload.filePathInSynFolder);
                            Program.ServerForm.addtoConsole("Deleted");
                            //***/
                        }
                    }
                }

                if (upload.addInfo.IndexOf("rename") == 0)
                {
                    // get container
                    CloudBlobContainer container = blobClient.GetContainerReference(upload.userName);

                    // get new path in the server
                    string[] separators = { "|||" };
                    string[] str = upload.addInfo.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    string newPath = str[1];

                    //grab the blob
                    CloudBlockBlob existBlob = container.GetBlockBlobReference(upload.filePathInSynFolder);
                    // create a new blob
                    CloudBlockBlob newBlob = container.GetBlockBlobReference(newPath);
                    //copy from the old blob
                    newBlob.StartCopyFromBlob(existBlob);
                    Program.ServerForm.addtoConsole("Created new blob");
                    newBlob.Metadata["hashValue"] = upload.fileHashValue;
                    newBlob.Metadata["timestamp"] = upload.fileTimeStamps.ToString("MM/dd/yyyy HH:mm:ss");
                    newBlob.Metadata["filePath"] = newPath;
                    newBlob.SetMetadata();
                    newBlob.CreateSnapshot();
                    //delete the old blob
                    existBlob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
                    Program.ServerForm.addtoConsole("Deleted old blob");
                }

            }
            catch (Exception e)
            {
                Program.ServerForm.addtoConsole("Exception [UploadReq]:"+ e.Message);
                //System.Windows.Forms.MessageBox.Show(e.ToString());
                //System.IO.File.WriteAllText("bug.txt", e.ToString());
            }
            finally
            {
                Program.ServerForm.addtoConsole("Exiting");
                Thread.CurrentThread.Abort();
            }
        }
예제 #7
0
파일: SignIn.cs 프로젝트: hangmiao/DBLike
        private static void threadStartFun(string serverIP, int port, String username, String password,Form frm)
        {
            //TBD
            Program.ClientForm.addtoConsole("Starting signin thread");
            //TBD
            if(username == "" || password == "")
            {
                Program.ClientForm.addtoConsole("Error : <<Username: \"" +username + "\" and Password: \"" +password + "\" >>" );
                //Program.ClientForm.addtoConsole("Password:"******"Username and Password field cannot be empty", "DBLike Client Sign In");
                if (!Program.ClientForm.IsHandleCreated)
                {
                    Program.ClientForm.CreateHandle();
                }
                //enable service controller
                Program.ClientForm.signinfail();
                Program.ClientForm.addtoConsole("Exiting");
                Thread.CurrentThread.Abort();
            }

            MessageClasses.MsgSignIn msgobj = new MessageClasses.MsgSignIn();

            msgobj.setUsername(username);
            msgobj.setPassword(password);

            // Fill out the content in msgobj

            //call CreateMsg.createSignUpMsg(msgobj) get it in bytes form
            Message.CreateMsg msg = new Message.CreateMsg();
            String message = msg.createSignInMsg(msgobj);

            //create a socket connection. you may need to create in Conection Manager
            sender = conn.connect(serverIP, port);
            if (sender == null)
            {
                //System.Windows.Forms.MessageBox.Show("Could not connect to server.Please check if Server is Running.", "DBLike Client");
                if (!Program.ClientForm.IsHandleCreated)
                {
                    Program.ClientForm.CreateHandle();
                }
                //enable service controller
                Program.ClientForm.addtoConsole("Error : <<Unable to connect to server>> ");
                Program.ClientForm.signinfail();
                Program.ClientForm.addtoConsole("Exiting");
                Thread.CurrentThread.Abort();
            }
            //call  SocketCommunication.ReaderWriter.write(byte[] msg) to write msg on socket
            SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
            Program.ClientForm.addtoConsole("Writing to socket");
            rw.writetoSocket(sender, message);
            //call  SocketCommunication.ReaderWriter.read() to read response from server
            String response = rw.readfromSocket(sender);
            Program.ClientForm.addtoConsole("Reading from socket");
            //call parser and process it.....
            Message.MessageParser mp = new Message.MessageParser();
            msgobj = mp.signInParseMessage(response);
            if(!msgobj.getAck().Equals(""))
            {
                if(msgobj.getAck()=="ERRORS")
                {
                    Program.ClientForm.addtoConsole("Error : <<" + msgobj.getAddiMsg() + ">>");
                    System.Windows.Forms.MessageBox.Show("AUTHENTICATION FAILED", "User name or Password incorrect");
                    if (!Program.ClientForm.IsHandleCreated)
                    {
                        Program.ClientForm.CreateHandle();
                    }
                    //enable service controller
                    Program.ClientForm.signinfail();
                    Program.ClientForm.addtoConsole("Exiting");
                    Thread.CurrentThread.Abort();
                }
                else
                {
                    //System.Windows.Forms.MessageBox.Show(msgobj.getAck(),msgobj.getAddiMsg());\
                    //Program.ClientForm.addtoConsole("Username:"******"Hello, "+ username +"! You have successfully signed in");
                    LocalDbAccess.LocalDB file = new LocalDbAccess.LocalDB();
                    file = file.readfromfile();
                    if (file != null)
                    {
                        if (username != file.getUsername() || password != file.getPassword())
                        {

                            if (DialogResult.Yes == System.Windows.Forms.MessageBox.Show("This System is already configured for a dblike user." +
                                "Do you really want to reconfigure it for another user?", "DBLike Client", MessageBoxButtons.YesNo))
                            {

                                string path = null;
                                System.Windows.Forms.MessageBox.Show("Please select a path to download your folder from the server");
                                var t = new Thread((ThreadStart)(() =>
                                {
                                    FolderBrowserDialog folder = new FolderBrowserDialog();
                                    if (folder.ShowDialog() == DialogResult.OK)
                                    {
                                        path = folder.SelectedPath;
                                    }
                                }));
                                t.IsBackground = true;
                                t.SetApartmentState(ApartmentState.STA);
                                t.Start();
                                t.Join();
                                //write to file
                                file = new LocalDbAccess.LocalDB();
                                file.writetofile(username, password, path);

                                Program.ClientForm.addtoConsole("Wrote to Config file");
                            }
                            else
                            {
                                Program.ClientForm.signinfail();
                                Program.ClientForm.addtoConsole("Exiting");
                                Thread.CurrentThread.Abort();
                            }
                        }
                    }
                    else
                    {
                        //System.Windows.Forms.MessageBox.Show("Localdb doesnot exist.");

                        string path = null;
                        System.Windows.Forms.MessageBox.Show("Please select a path to download your folder from the server");
                        var t = new Thread((ThreadStart)(() =>
                        {
                            FolderBrowserDialog folder = new FolderBrowserDialog();
                            if (folder.ShowDialog() == DialogResult.OK)
                            {
                                path = folder.SelectedPath;
                            }
                        }));

                        t.IsBackground = true;
                        t.SetApartmentState(ApartmentState.STA);
                        t.Start();
                        t.Join();
                        //write to file
                        file = new LocalDbAccess.LocalDB();
                        file.writetofile(username, password, path);

                        Program.ClientForm.addtoConsole("Wrote to Confgi file");

                    }
                    //poll = new PollFiles();
                    if (!Program.ClientForm.IsHandleCreated)
                    {
                        Program.ClientForm.CreateHandle();
                    }
                    //enable service controller
                    Program.ClientForm.signinpass();

                    Program.ClientForm.addtoConsole("Successefully Signed in");
                    //poll.start();
                    //MessageBox.Show("Signing in done","Client");
                    Client.Program.poll.pull = true;
                    Client.Program.poll.start();
                    Program.ClientForm.addtoConsole("Polling started");
                    //Thread.Sleep(10000);

                    // initialize the file list for sign in scenario
                    Client.LocalFileSysAccess.FileListMaintain fileMaintain = new Client.LocalFileSysAccess.FileListMaintain();
                    fileMaintain.scanAllFilesAttributes();

                    //FileSysWatchDog.Run();
                    Program.folderWatcher.start();
                    Program.ClientForm.addtoConsole("File-watcher Installed");
                    //Program.ClientForm.ballon("File watcher installed");
                    Thread.CurrentThread.Abort();
                }
            }
        }
예제 #8
0
        public static void listen()
        {
            //System.Windows.Forms.MessageBox.Show("Servermainthread started", "Server");

            Program.ServerForm.addtoConsole("Starting Server...");
            //**************setting to connect to local server **********************
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
            //***************************************************************************/

            /*************** Setting to run on VM*******************************
            // Iterate through IP list and find IPV4

            bool found = false;
            int i = 0;
            IPAddress ipAddress = null;

            String strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
            while (!found)
            {
                if (!iphostentry.AddressList[i].IsIPv6LinkLocal)
                {
                    ipAddress = iphostentry.AddressList[i];
                    found = true;
                }
                i++;
                if (i == 10)
                {
                    found = true;
                }
            }
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
            *********************************************************************/

            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);
                Program.ServerForm.addtoConsole("Server started");
                while(true)
                {
                    Program.ServerForm.addtoConsole("Listening...");
                    handler = listener.Accept();
                    Program.ServerForm.addtoConsole("Received Conn from "+ ((IPEndPoint)handler.RemoteEndPoint).Address.ToString());
                    if (varstop)
                    {
                        Program.ServerForm.addtoConsole("Shutting down...");
                        //if (DialogResult.Yes == MessageBox.Show("Do you really want to shut down server? ", "Allow", MessageBoxButtons.YesNo))
                        //{
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            //Application.Exit();
                            break;
                        //}
                        //varstop = false;
                    }
                    //TBD
                    /*
                    byte[] str = new byte[1024];
                    handler.Receive(str);
                    Console.WriteLine(str.ToString());
                    System.Windows.Forms.MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));
                     */
                    SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();

                    string req = rw.readfromSocket(handler);
                    Program.ServerForm.addtoConsole(req);
                    string reqtype = findReqType(req);
                    switch(reqtype)
                    {
                        case "SIGNUP":
                            {
                                //System.Windows.Forms.MessageBox.Show("Switch signUp", "Server");
                                Program.ServerForm.addtoConsole("Request Type:" + reqtype);
                                Threads.ServiceSignUpReq obj = new ServiceSignUpReq();
                                obj.start(handler, req);
                                break;
                            }

                        case "SIGNIN":
                            {
                                Program.ServerForm.addtoConsole("Request Type:" + reqtype);
                                ServiceSignInReq obj = new ServiceSignInReq();
                                obj.start(handler, req);
                                break;
                            }

                        case "POLL":
                            {
                                Program.ServerForm.addtoConsole("Request Type:" + reqtype);
                                ServicePollReq obj = new ServicePollReq();
                                obj.start(handler, req);
                                break;
                            }

                        case "UPLOAD":
                            {
                                Program.ServerForm.addtoConsole("Request Type:" + reqtype);
                                //System.Windows.Forms.MessageBox.Show("Switch Upload", "Server");
                                ServiceUploadReq obj = new ServiceUploadReq();
                                obj.start(handler, req);
                                //obj.stop();
                                break;
                            }

                        case "DOWNLOAD":
                            {
                                Program.ServerForm.addtoConsole("Request Type:" + reqtype);
                                ServiceDownloadReq obj = new ServiceDownloadReq();
                                obj.start(handler, req);
                                break;
                            }

                        case "NOTIFICATION":
                            {
                                Program.ServerForm.addtoConsole("Request Type:" + reqtype);
                                Service_Notification obj = new Service_Notification();
                                obj.start(handler, req);
                                break;
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                Program.ServerForm.addtoConsole(ex.ToString());
            }
        }
예제 #9
0
        private void threadStartFun(Socket soc, string req)
        {
            Program.ServerForm.addtoConsole("Service SignUpReq Thread Started");
            //parse msg received
            //System.Windows.Forms.MessageBox.Show("Signup service started:"+ req, "Server");
            Message.MessageParser parser = new Message.MessageParser();
            MessageClasses.MsgSignUp.req reqobj = new MessageClasses.MsgSignUp.req();
            reqobj = parser.signUpParseReq(req);

            //create connection with sql
            ConnectionManager.DataBaseConn con = new ConnectionManager.DataBaseConn(1);
            SqlConnection conn = con.DBConnect();
            //check if user already exits
            DatabaseAccess.Query q = new DatabaseAccess.Query();

            if (true == q.checkIfUserExists(reqobj.userName, conn))
            {
                con.DBClose();
                //System.Windows.Forms.MessageBox.Show("Signup service if user exists", "Server");
                MessageClasses.MsgSignUp.resp resp = new MessageClasses.MsgSignUp.resp();
                resp.ack = "ERRORS";
                resp.addiMsg = "AlreadyExist";
                Message.CreateMsg msg = new Message.CreateMsg();
                string res=  msg.signUpResp(resp);
                SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                rw.writetoSocket(soc, res);
                Program.ServerForm.addtoConsole("Writing response to Socket");
                Program.ServerForm.addtoConsole("Exiting");
                Thread.CurrentThread.Abort();
            }
            else
            {
                ConnectionManager.DataBaseConn con1 = new ConnectionManager.DataBaseConn(1);
                SqlConnection conn1 = con.DBConnect();
                if (true == q.insertNewUser(reqobj.userName, reqobj.psw, conn1))
                {

                    Program.ServerForm.addtoConsole("New User Added");
                    conn1.Close();
                    //System.Windows.Forms.MessageBox.Show("Signup service insert user", "Server");
                    MessageClasses.MsgSignUp.resp resp = new MessageClasses.MsgSignUp.resp();
                    resp.ack = "OK";
                    resp.addiMsg = "Added";
                    Message.CreateMsg msg = new Message.CreateMsg();
                    string res = msg.signUpResp(resp);
                    SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                    rw.writetoSocket(soc, res);
                    Program.ServerForm.addtoConsole("Wrote response to Socket");

                    //conn.Close();
                }
                else
                {
                    conn1.Close();
                    Program.ServerForm.addtoConsole("Sign Up Error while inserting to Database");
                    //System.Windows.Forms.MessageBox.Show("Signup service could insert", "Server");
                    MessageClasses.MsgSignUp.resp resp = new MessageClasses.MsgSignUp.resp();
                    resp.ack = "ERRORS";
                    resp.addiMsg = "ERRORWHILEINSERTING";
                    Message.CreateMsg msg = new Message.CreateMsg();
                    string res = msg.signUpResp(resp);
                    SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
                    rw.writetoSocket(soc, res);
                    Program.ServerForm.addtoConsole("Wrote Respose to Socket");
                    //conn.Close();
                }
                //conn.Close();
                Program.ServerForm.addtoConsole("Exiting");
                Thread.CurrentThread.Abort();
            }
            //TBD
        }
예제 #10
0
파일: SignUp.cs 프로젝트: hangmiao/DBLike
        private static void threadStartFun(string serverIP, int port,String username, String password,string sysncpath )
        {
            Program.ClientForm.addtoConsole("Sign Up initiated");
            //TBD
            //System.Windows.Forms.MessageBox.Show("start", "SignUp Thread started");
            MessageClasses.MsgSignUp msgobj = new MessageClasses.MsgSignUp();
            msgobj.userName = username;
            msgobj.psw = password;
            // Fill out the content in msgobj

            //call CreateMsg.createSignUpMsg(msgobj) get it in bytes form
            Message.CreateMsg msg=new Message.CreateMsg();
            String message = msg.createSignUpMsg(msgobj);

            //create a socket connection. you may need to create in Conection Manager
            sender = conn.connect(serverIP, port);
            if(sender == null)
            {
                Program.ClientForm.addtoConsole("Error : <<Could not connect to server. May be Server is not Running>>");
                //System.Windows.Forms.MessageBox.Show("Could not connect to server.Please check if Server is Running.", "DBLike Client");
                Program.ClientForm.addtoConsole("Exiting");
                Program.ClientForm.signupfail();
                Thread.CurrentThread.Abort();
            }
            //call  SocketCommunication.ReaderWriter.write(byte[] msg) to write msg on socket
            SocketCommunication.ReaderWriter rw = new SocketCommunication.ReaderWriter();
            //System.Windows.Forms.MessageBox.Show("going to write socket:"+message, "SignUp Thread started");
            Program.ClientForm.addtoConsole("Writing to socket: " + message);
            rw.writetoSocket(sender, message);

            //call  SocketCommunication.ReaderWriter.read() to read response from server
            //System.Windows.Forms.MessageBox.Show("going to read socket: " , "SignUp Thread started");
            String response=rw.readfromSocket(sender);
            Program.ClientForm.addtoConsole("Read from socket :" + response);
            //System.Windows.Forms.MessageBox.Show("read:"+ response, "SignUp Thread started");
            //call parser and process it.....
            Message.MessageParser mp = new Message.MessageParser();

            //msgobj = mp.signInParseMessage(response);
            msgobj = mp.signUpParseMessage(response);

            // This functionality should be added here

            //call parser and process it.....
            if (!msgobj.ack.Equals(""))
            {
                Message.MessageParser msgparser = new Message.MessageParser();
                if (msgobj.ack.Equals("ERRORS"))
                {
                    Program.ClientForm.addtoConsole("Error :" +"<<"+ msgobj.addiMsg +">>");
                    //System.Windows.Forms.MessageBox.Show("Some error occured!Please try again.", "Error Occured");
                    Program.ClientForm.addtoConsole("Exiting");
                    Program.ClientForm.signupfail();
                    Thread.CurrentThread.Abort();
                }
                else
                {
                    Program.ClientForm.ballon("Congratulations " + username + "! Your account is successfully created");
                    if (File.Exists(@"C:\dblikeConfig\dblike.txt"))
                    {
                        if (DialogResult.No == System.Windows.Forms.MessageBox.Show("This System is already configured for a dblike user." +
                            "Do you want to reconfigure it for yourself?", "DBLike Client", MessageBoxButtons.YesNo))
                        {
                            Program.ClientForm.addtoConsole("Exiting");
                            Program.ClientForm.signupfail();
                            Thread.CurrentThread.Abort();
                        }
                    }
                    /*
                    if (!Program.ClientForm.IsHandleCreated)
                    {
                        Program.ClientForm.CreateHandle();
                    }
                    Program.ClientForm.Appendconsole("Successefully Signed in");
                     */
                    LocalDbAccess.LocalDB file = new LocalDbAccess.LocalDB();
                    if (false == file.writetofile(username, password, sysncpath))
                    {
                        Program.ClientForm.addtoConsole("Error : <<Unable to access config file. Please try Sign In>>");
                        //System.Windows.Forms.MessageBox.Show("Unable to access dblike file. Please try Sign In.", "Error Occured");
                        Program.ClientForm.addtoConsole("Exiting");
                        Program.ClientForm.signupfail();
                        Thread.CurrentThread.Abort();
                    }
                    else
                    {

                        //Upload all the content
                        bool result = file.writetofile(username, password, sysncpath);
                        if (result == false)
                        {
                            Program.ClientForm.addtoConsole("Error : <<Unable to access config file. Please try Sign In>>");
                            //System.Windows.Forms.MessageBox.Show("Unable to write on the file. Please try Sign In.", "Unable to write on file");
                            Program.ClientForm.addtoConsole("Exiting");
                            Program.ClientForm.signupfail();
                            Thread.CurrentThread.Abort();
                            //return;
                        }
                        Program.ClientForm.addtoConsole("Initiating content upload");
                        uploadeverything(sysncpath);
                        //System.Windows.Forms.MessageBox.Show("Uploaded!!!", "Client");
                        //System.Windows.Forms.MessageBox.Show("Started!!!", "Client");

                        // initialize the file list for sign up scenario
                        Client.LocalFileSysAccess.FileListMaintain fileMaintain = new Client.LocalFileSysAccess.FileListMaintain();
                        fileMaintain.scanAllFilesAttributes();

                        Program.folderWatcher.start();
                        Program.ClientForm.addtoConsole("File watcher Installed");

                        Client.Program.poll.start();
                        Program.ClientForm.addtoConsole("Poll thread started");

                        if (!Program.ClientForm.IsHandleCreated)
                        {
                            Program.ClientForm.CreateHandle();
                        }
                        //enable service controller
                        Program.ClientForm.signUppassed();

                        /*
                        Threads.FileSysWatchDog watchdog = new FileSysWatchDog();
                        if (watchdog.start() == false)
                        {
                            //disable stop service button
                            //enable start service button
                        }
                         */
                    }
                    Program.ClientForm.addtoConsole("Exiting Sign Up thread");
                    Thread.CurrentThread.Abort();
                }
            }
        }