public void FileSystemQuery_ShareCollection()
        {
            var shareCollection = new ShareCollection(@"\\DEVOPSPDC.premier.local\");

            //------------Assert Results-------------------------
            Assert.IsTrue(shareCollection.Count > 0, "Cannot get shared directory information.");
        }
Beispiel #2
0
        private ShareCollection ReadShareSettings()
        {
            ShareCollection shares = new ShareCollection();
            string          executableDirectory = Path.GetDirectoryName(Application.ExecutablePath) + "\\";
            XmlDocument     document            = GetXmlDocument(executableDirectory + SettingsFileName);
            XmlNode         sharesNode          = document.SelectSingleNode("Settings/Shares");

            foreach (XmlNode shareNode in sharesNode.ChildNodes)
            {
                if (shareNode.Name.Equals("DirectoryShare", StringComparison.OrdinalIgnoreCase))
                {
                    string shareName = shareNode.Attributes["Name"].Value;
                    string sharePath = shareNode.Attributes["Path"].Value;

                    shares.Add(shareName, new string[] { "*" }, new string[] {},
                               new DirectoryFileSystem(sharePath));
                }
                else if (shareNode.Name.Equals("DropShare", StringComparison.OrdinalIgnoreCase))
                {
                    string shareName = shareNode.Attributes["Name"].Value;
                    string account   = shareNode.Attributes["Account"].Value;
                    string key       = shareNode.Attributes["Key"].Value;
                    shares.Add(shareName, new string[] { "*" }, new string[] { },
                               new AzureFileSystem(account, key));
                }
                else
                {
                    throw new Exception("invalid config " + shareNode.Name);
                }
            }



            return(shares);
        }
Beispiel #3
0
        public override bool BeforeExecute(int operatorUserID, string param, ref long offset, ref int totalCount, out string title)
        {
            StringList paramData = StringList.Parse(param);

            ShareFilter filter = ShareFilter.Parse(paramData[0]);

            //只取一条数据测试下就可以
            filter.PageSize = 1;

            ShareCollection shares = null;

            if (paramData[2] == "share")
            {
                shares = ShareBO.Instance.GetSharesForAdmin(operatorUserID, filter, 1);
            }
            else
            {
                shares = FavoriteBO.Instance.GetSharesForAdmin(operatorUserID, filter, 1);
            }

            if (shares == null || shares.Count == 0)
            {
                title = "没有数据可以删除";
                return(false);
            }

            totalCount = shares.TotalRecords;

            title = "将删除 " + totalCount + " 条" + (paramData[2] == "share" ? "分享" : "收藏");

            return(true);
        }
Beispiel #4
0
        /**
         * static function to get list of folders on
         * the network name so provided
         */
        public static ArrayList get_folders(string server)
        {
            ArrayList folders = new ArrayList();

            if (server != null && server.Trim().Length > 0)
            {
                ShareCollection shi = ShareCollection.GetShares(server);
                if (shi != null)
                {
                    foreach (Share si in shi)
                    {
                        if (si.ShareType.ToString() == "Disk")
                        {
                            folders.Add(si.ToString());
                        }
                    }
                }
                else
                {
                    folders.Add("-1");
                    return(folders);
                }
            }
            return(folders);
        }
        public void FileSystemQuery_ShareCollection()
        {
            //------------Setup for test--------------------------
            var shareCollection = new ShareCollection(@"\\tst-ci-remote\");

            Assert.AreEqual(5, shareCollection.Count);
        }
Beispiel #6
0
        public void FileSystemQuery_ShareCollection()
        {
            //------------Execute Test---------------------------
            var shareCollection = new ShareCollection(@"\\rsaklfsvrpdc\");

            //------------Assert Results-------------------------
            Assert.AreEqual(17, shareCollection.Count);
        }
Beispiel #7
0
            /// <summary>
            /// Enumerates the shares on Windows 9x
            /// </summary>
            /// <param name="server">The server name</param>
            /// <param name="shares">The ShareCollection</param>
            protected static void EnumerateShares9x(string server, ShareCollection shares)
            {
                int    level = 50;
                int    nRet = 0;
                ushort entriesRead, totalEntries;

                Type   t        = typeof(SHARE_INFO_50);
                int    size     = Marshal.SizeOf(t);
                ushort cbBuffer = (ushort)(MAX_SI50_ENTRIES * size);
                //On Win9x, must allocate buffer before calling API
                IntPtr pBuffer = Marshal.AllocHGlobal(cbBuffer);

                try
                {
                    nRet = NetShareEnum(server, level, pBuffer, cbBuffer,
                                        out entriesRead, out totalEntries);

                    if (ERROR_WRONG_LEVEL == nRet)
                    {
                        level = 1;
                        t     = typeof(SHARE_INFO_1_9x);
                        size  = Marshal.SizeOf(t);

                        nRet = NetShareEnum(server, level, pBuffer, cbBuffer,
                                            out entriesRead, out totalEntries);
                    }

                    if (NO_ERROR == nRet || ERROR_MORE_DATA == nRet)
                    {
                        for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += size)
                        {
                            IntPtr pItem = new IntPtr(lpItem);

                            if (1 == level)
                            {
                                SHARE_INFO_1_9x si = (SHARE_INFO_1_9x)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                            }
                            else
                            {
                                SHARE_INFO_50 si = (SHARE_INFO_50)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine(nRet);
                    }
                }
                finally
                {
                    //Clean up buffer
                    Marshal.FreeHGlobal(pBuffer);
                }
            }
Beispiel #8
0
            /// <summary>
            /// Enumerates the shares on Windows NT
            /// </summary>
            /// <param name="server">The server name</param>
            /// <param name="shares">The ShareCollection</param>
            protected static void EnumerateSharesNT(string server, ShareCollection shares)
            {
                int    level = 2;
                int    entriesRead, totalEntries, nRet, hResume = 0;
                IntPtr pBuffer = IntPtr.Zero;

                try
                {
                    nRet = NetShareEnum(server, level, out pBuffer, -1,
                                        out entriesRead, out totalEntries, ref hResume);

                    if (ERROR_ACCESS_DENIED == nRet)
                    {
                        //Need admin for level 2, drop to level 1
                        level = 1;
                        nRet  = NetShareEnum(server, level, out pBuffer, -1,
                                             out entriesRead, out totalEntries, ref hResume);
                    }

                    if (NO_ERROR == nRet && entriesRead > 0)
                    {
                        Type t      = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1);
                        int  offset = Marshal.SizeOf(t);

                        for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += offset)
                        {
                            IntPtr pItem = new IntPtr(lpItem);
                            if (1 == level)
                            {
                                SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                            }
                            else
                            {
                                SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                            }
                        }
                    }
                }
                finally
                {
                    // Clean up buffer allocated by system
                    if (IntPtr.Zero != pBuffer)
                    {
                        NetApiBufferFree(pBuffer);
                    }
                }
            }
Beispiel #9
0
        public IList <IShare> GetShareList(List <String> toolNameList)
        {
            // using the solution from code-project (Richard Deeming)
            // https://www.codeproject.com/Articles/2939/Network-Shares-and-UNC-paths

            List <IShare> shareList = new List <IShare>();

            List <string> pcList = GetComputersListOnNetwork();

            if (pcList.Count == 0)
            {
                Logger?.InfoLog("The arrived computerlist is empty.", CLASS_NAME);
                return(shareList);
            }

            try
            {
                foreach (string pcName in pcList)
                {
                    // get list of shares on the PC
                    ShareCollection shareColl = ShareCollection.GetShares(pcName);

                    //get all files of each share:
                    foreach (Share sh in shareColl)
                    {
                        try
                        {
                            bool checkThekList = toolNameList.Any(p => sh.NetName.Contains(p));

                            if (sh.IsFileSystem && sh.ShareType == ShareType.Disk && checkThekList)
                            {
                                shareList.Add(new ShareAdapter(sh));
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger?.ErrorLog($"Exception occured: {ex}", CLASS_NAME);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.ErrorLog($"Exception occured: {ex}", CLASS_NAME);
            }

            return(shareList);
        }
        public void FileSystemQuery_ShareCollection()
        {
            var shareCollection = new ShareCollection(@"\\rsaklfsvrpdc.dev2.local\");

            if (shareCollection.Count <= 0)
            {
                var username = @"dev2\IntegrationTester";
                var password = TestEnvironmentVariables.GetVar(username);
                //------------Execute Test---------------------------
                AuthenticateForSharedFolder(@"\\rsaklfsvrpdc.dev2.local\apps", username, password);
                Thread.Sleep(1000);
                shareCollection = new ShareCollection(@"\\rsaklfsvrpdc.dev2.local\");
            }
            //------------Assert Results-------------------------
            Assert.IsTrue(shareCollection.Count > 0, "Cannot get shared directory information.");
        }
Beispiel #11
0
		public override ShareCollection GetUserFavorites(int favOwnerID, ShareType? favType, int pageNumber, int pageSize, ref int? totalCount)
		{
			using (SqlQuery query = new SqlQuery())
			{
                query.Pager.TableName = "[bx_SharesView]";
				query.Pager.SortField = "[ShareID]";
				query.Pager.IsDesc = true;
				query.Pager.PageNumber = pageNumber;
				query.Pager.PageSize = pageSize;
				query.Pager.TotalRecords = totalCount;
				query.Pager.SelectCount = true;

				SqlConditionBuilder cb = new SqlConditionBuilder(SqlConditionStart.None);

				cb.Append("[UserID] = @UserID");

				query.CreateParameter<int>("@UserID", favOwnerID, SqlDbType.Int);

				if (favType.HasValue && favType.Value != ShareType.All)
				{
					cb.Append("[Type] = @Type");

					query.CreateParameter<ShareType>("@Type", favType.Value, SqlDbType.TinyInt);
				}

				cb.Append("[PrivacyType] = 2");

				query.Pager.Condition = cb.ToString();

				using (XSqlDataReader reader = query.ExecuteReader())
				{
                    ShareCollection shares = new ShareCollection(reader);

                    if (reader.NextResult())
					{
                        if (totalCount == null && reader.Read())
						{
                            totalCount = reader.Get<int>(0);
						}

						shares.TotalRecords = totalCount.GetValueOrDefault();
					}

					return shares;
				}
			}
		}
Beispiel #12
0
        void GetShares(string Host)
        {
            TreeNode        TNc = new TreeNode(Host);
            ShareCollection shi;

            TNc.Tag                = Host;
            TNc.ImageIndex         = 0;
            TNc.SelectedImageIndex = TNc.ImageIndex;
            int CurrIndex = 0;

            if (Host == "LocalHost")
            {
                shi = ShareCollection.LocalShares;
            }
            else
            {
                shi = ShareCollection.GetShares(Host);
            }
            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    TreeNode TN = new TreeNode(si.NetName + "");
                    TN.Tag = si.ToString() + "";
                    if (si.ShareType == ShareType.Special)
                    {
                        TN.ImageIndex = 1;

                        TN.SelectedImageIndex = TN.ImageIndex;
                        TNc.Nodes.Insert(CurrIndex, TN);
                        CurrIndex += 1;
                    }
                    else
                    {
                        TN.ImageIndex         = 2;
                        TN.SelectedImageIndex = TN.ImageIndex;
                        TNc.Nodes.Add(TN);
                    }
                }
                TNc.Expand();
                treeView1.Nodes.Add(TNc);
                treeView1.TreeViewNodeSorter = new NodeSorter();
            }
        }
Beispiel #13
0
        private bool ValidatePath(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    return(true);
                }

                if (path.StartsWith("\\\\"))
                {
                    ShareCollection shares = ShareCollection.GetShares(path);
                    return(shares != null && shares.Count > 0);
                }
            }
            catch { }

            return(false);
        }
Beispiel #14
0
        public ArrayList GetNetworkShareFoldersList(string serverName)
        {
            ArrayList shares = new ArrayList();

            //Split each and go back one
            string[] parts = serverName.Split('\\');

            //Could not happend if stated as \\server\path\
            if (parts.Length < 3)
            {
                SetErrorString(@"GetNetworkShareFoldersList did not get a \\server\path as expected");
                return(shares);
            }

            string          server = @"\\" + parts[2] + @"\";
            ShareCollection shi    = ShareCollection.LocalShares;

            if (server != null && server.Trim().Length > 0)
            {
                shi = ShareCollection.GetShares(server);
                if (shi != null)
                {
                    foreach (Share si in shi)
                    {
                        //We only want the disks
                        if (si.ShareType == ShareType.Disk || si.ShareType == ShareType.Special)
                        {
                            DirectoryBrowse aDir = new DirectoryBrowse();
                            aDir.sPath = si.Root.FullName + @"\";
                            aDir.sName = si.NetName;
                            shares.Add(aDir);
                        }
                    }
                }
                else
                {
                    SetErrorString(@"Unable to enumerate the shares on " + server + " - Make sure the machine exists and that you have permission to access it");
                    return(new ArrayList());
                }
            }
            return(shares);
        }
Beispiel #15
0
        public void TestInitiateSecretWith_Y_P_Array()
        {
            SecretSharingCore.Algorithms.Shamir shamir = new SecretSharingCore.Algorithms.Shamir();
            var n      = 10;
            var k      = 3;
            var secret = 1234;
            //assign
            var shares          = shamir.DivideSecret(k, n, secret);
            var initiatedShares = new List <IShareCollection>();

            //assert
            Assert.AreEqual(shares.Count, n);
            int j = 0;

            foreach (var col in shares)
            {
                j++;
                IShareCollection collection = new ShareCollection();
                for (int i = 0; i < col.GetCount(); i++)
                {
                    Assert.IsNotNull(col.GetShare(i).GetY());
                    Assert.IsNotNull(col.GetShare(i).GetP());

                    ShamirShare myshare = new ShamirShare(col.GetShare(i).GetX(), col.GetShare(i).GetY()
                                                          , col.GetShare(i).GetP());

                    Assert.AreEqual(col.GetShare(i).ToString(), myshare.ToString());
                    collection.SetShare(i, myshare);
                }
                initiatedShares.Add(collection);
                if (j == k)
                {
                    break;
                }
            }

            var reconsecret = shamir.ReconstructSecret(initiatedShares);

            Assert.AreEqual(secret, reconsecret);
        }
Beispiel #16
0
        void RemoteShares(string ServerName)
        {
            ShareCollection shi = ShareCollection.GetShares(ServerName);

            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    Console.WriteLine("{0}: {1} [{2}]",
                                      si.ShareType, si, si.Path);

                    // If this is a file-system share, try to
                    // list the first five subfolders.
                    // NB: If the share is on a removable device,
                    // you could get "Not ready" or "Access denied"
                    // exceptions.
                    // If you don't have permissions to the share,
                    // you will get security exceptions.
                    if (si.IsFileSystem)
                    {
                        try
                        {
                            System.IO.DirectoryInfo   d    = si.Root;
                            System.IO.DirectoryInfo[] Flds = d.GetDirectories();
                            for (int i = 0; i < Flds.Length && i < 5; i++)
                            {
                                Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);
                            }

                            Console.WriteLine();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                                              si.ToString(), ex.Message);
                        }
                    }
                }
            }
        }
Beispiel #17
0
            /// <summary>
            /// Enumerates the shares
            /// </summary>
            /// <param name="server">The server name</param>
            /// <param name="shares">The ShareCollection</param>
            protected static void EnumerateShares(string server, ShareCollection shares)
            {
                if (null != server && 0 != server.Length && !IsW2KUp)
                {
                    server = server.ToUpper();

                    // On NT4, 9x and Me, server has to start with "\\"
                    if (!('\\' == server[0] && '\\' == server[1]))
                    {
                        server = @"\\" + server;
                    }
                }

                if (IsNT)
                {
                    EnumerateSharesNT(server, shares);
                }
                else
                {
                    EnumerateShares9x(server, shares);
                }
            }
Beispiel #18
0
        static string GetLocalPath(string netfile)
        {
            string server = getServer(netfile);

            if (server == null)
            {
                exitProgram(Properties.Resources.SERVER_NULL);
            }
            if (server.ToLower() != Environment.MachineName.ToLower())
            {
                return(null);
            }

            ShareCollection shi = ShareCollection.LocalShares;

            if (shi == null)
            {
                exitProgram(Properties.Resources.SHARECOLLECTION_NULL);
            }

            string serverandshare = getServerAndShare(netfile);

            if (serverandshare == null)
            {
                exitProgram(Properties.Resources.SERVERANDSHARE_NULL);
            }
            foreach (Share si in shi)
            {
                if (si.ShareType == ShareType.Disk && si.IsFileSystem)
                {
                    if (serverandshare.ToLower() == si.ToString().ToLower())
                    {
                        return(ReplaceFirst(netfile, serverandshare, si.Path));
                    }
                }
            }
            return(null);
        }
Beispiel #19
0
        static int TestShares(string server)
        {
            ShareCollection shi;

            if (server != null && server.Trim().Length > 0)
            {
                shi = ShareCollection.GetShares(server);
                if (shi != null)
                {
                    foreach (Share si in shi)
                    {
                        if (si.IsFileSystem)
                        {
                            Console.WriteLine("{0}", si);
                        }
                    }
                }
                else
                {
                    return(-1);
                }
            }
            return(0);
        }
Beispiel #20
0
            /// <summary>
            /// Returns the local <see cref="Share"/> object with the best match
            /// to the specified path.
            /// </summary>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static Share PathToShare(string fileName)
            {
                if (null == fileName || 0 == fileName.Length)
                {
                    return(null);
                }

                fileName = Path.GetFullPath(fileName);
                if (!IsValidFilePath(fileName))
                {
                    return(null);
                }

                ShareCollection shi = LocalShares;

                if (null == shi)
                {
                    return(null);
                }
                else
                {
                    return(shi[fileName]);
                }
            }
Beispiel #21
0
        /// <summary>
        /// Arbeitet einen FileServer ab
        /// </summary>
        /// <param name="server"></param>
        static void WorkOnFileServer(ConfigServer server)
        {
            // Liest die Shares des Servers aus
            ShareCollection shareColl = ShareCollection.GetShares(server.Name);

            // Wenn keine Shares gelesen werden konnten
            if (shareColl == null)
            {
                return;
            }

            int shareIndex = 1;

            // Schleife über jede ausgelesene Freigabe
            foreach (Share share in shareColl)
            {
                Log.write(shareIndex + "/" + shareColl.Count + " - " + share.NetName + " wird ausgelesen...", true, false);
                // Ruft alle Informationen ab und schreibt sie in die Datenbank
                FSWorker.GetSharesSecurity(share, server.DisplayName);

                Log.write(" fertig", false, true);
                shareIndex++;
            }
        }
Beispiel #22
0
		public override ShareCollection GetUserShares(int shareOwnerID, ShareType? shareType, DataAccessLevel dataAccessLevel, int pageNumber, int pageSize, ref int? totalCount)
		{
			using (SqlQuery query = new SqlQuery())
			{
                query.Pager.TableName = "[bx_SharesView]";
				query.Pager.SortField = "[UserShareID]";
				query.Pager.IsDesc = true;
				query.Pager.PageNumber = pageNumber;
				query.Pager.PageSize = pageSize;
				query.Pager.TotalRecords = totalCount;
				query.Pager.SelectCount = true;

				SqlConditionBuilder cb = new SqlConditionBuilder(SqlConditionStart.None);

				cb.Append("[UserID2] = @UserID");

				query.CreateParameter<int>("@UserID", shareOwnerID, SqlDbType.Int);

				if (shareType.HasValue && shareType.Value != ShareType.All)
				{
					cb.Append("[Type] = @Type");

					query.CreateParameter<ShareType>("@Type", shareType.Value, SqlDbType.TinyInt);
				}

				if (dataAccessLevel == DataAccessLevel.Normal)
				{
					cb.Append("[PrivacyType] IN (0, 3)");
				}
				else if (dataAccessLevel == DataAccessLevel.Friend)
				{
					cb.Append("[PrivacyType] IN (0, 1, 3)");
				}
				else if(dataAccessLevel == DataAccessLevel.DataOwner)
				{
					cb.Append("[PrivacyType] != 2");
				}

				query.Pager.Condition = cb.ToString();

                ShareCollection shares;
				using (XSqlDataReader reader = query.ExecuteReader())
				{
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
					{
                        if (totalCount == null && reader.Read())
						{
                            totalCount = reader.Get<int>(0);
						}

						shares.TotalRecords = totalCount.GetValueOrDefault();
					}

				}
                FillComments(shares, query);

				return shares;
			}
		}
Beispiel #23
0
        public override ShareCollection GetAllUserShares(ShareType shareType, int pageNumber, int pageSize, out int totalCount)
        {
            totalCount = 0;
            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.IsDesc = true;
                query.Pager.SortField = "UserShareID";
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                //query.Pager.TotalRecords = totalCount;
                query.Pager.SelectCount = true;
                query.Pager.TableName = "[bx_SharesView]";
                query.Pager.Condition = @"
    (@ShareType = 0 OR [Type] = @ShareType)
AND 
    [PrivacyType] = 0
";

                query.CreateParameter<int>("@ShareType", (int)shareType, SqlDbType.TinyInt);

                ShareCollection shares;
                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            totalCount = reader.Get<int>(0);
                        }
                    }
                }
                FillComments(shares, query);
                return shares;
            }

        }
        private void Explore(bool keepSelection)
        {
            if (InvokeRequired)
            {
                Invoke(new ExploreHandler(Explore), keepSelection);
                return;
            }

            List <string> selection = new List <string>();

            if (keepSelection)
            {
                selection.AddRange(SelectedPaths);
            }

            int selIdx = 0;

            try
            {
                selIdx = this.SelectedIndices[0];
            }
            catch
            {
                selIdx = 0;
            }

            lock (syncRoot)
            {
                try
                {
                    ignoreEvents = true;

                    bool isUncPathRoot = false;

                    CursorHelper.ShowWaitCursor(this, true);

                    // Check if current path is valid.
                    if (!Directory.Exists(m_strDirPath))
                    {
                        m_strDirPath = FindFirstUsablePath(m_strDirPath, ref isUncPathRoot);
                    }

                    AppConfig.LastExploredFolder = m_strDirPath;

                    if (!isUncPathRoot && PathUtils.IsRootPath(m_strDirPath))
                    {
                        m_strDirPath = m_strDirPath.TrimEnd(string.Copy(PathUtils.DirectorySeparator).ToCharArray()) + PathUtils.DirectorySeparator;
                    }

                    ShareCollection shares = null;
                    List <string>   dirs   = null;
                    List <string>   files  = null;

                    if (isUncPathRoot)
                    {
                        try
                        {
                            shares = ShareCollection.GetShares(m_strDirPath);
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            dirs = PathUtils.EnumDirectories(m_strDirPath);
                        }
                        catch { }

                        try
                        {
                            files = PathUtils.EnumFilesUsingMultiFilter(m_strDirPath, this.SearchPattern);
                        }
                        catch { }
                    }

                    ClearCurrentContents();

                    CreateParentFolderRow();

                    if (isUncPathRoot && shares != null)
                    {
                        foreach (Share share in shares)
                        {
                            if (!share.IsFileSystem)
                            {
                                continue;
                            }

                            if (Directory.Exists(share.Root.FullName) == false)
                            {
                                continue;
                            }

                            CreateNewRow(share.Root.FullName);
                        }
                    }
                    else
                    {
                        if (dirs != null)
                        {
                            foreach (string dir in dirs)
                            {
                                if (Directory.Exists(dir) == false)
                                {
                                    continue;
                                }

                                CreateNewRow(dir);
                                int tt = 0;
                            }
                        }

                        if (files != null)
                        {
                            foreach (string file in files)
                            {
                                if (File.Exists(file) == false)
                                {
                                    continue;
                                }

                                CreateNewRow(file);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                }
                finally
                {
                    CursorHelper.ShowWaitCursor(this, false);
                    ignoreEvents = true;
                }

                if (this.Items.Count <= 0)
                {
                    CreateMessageRow(string.Empty);
                    CreateMessageRow(Translator.Translate("TXT_FOLDERNOTACCESSIBLE"));
                }
            }

            this.Sort();

            //ClearSelection();
            this.SelectedItems.Clear();

            bool selectedSomething = false;

            if (keepSelection || _pathToSelect != null)
            {
                if ((selection != null && selection.Count > 0) || _pathToSelect != null)
                {
                    bool focusSet = false;

                    foreach (ListViewItem item in Items)
                    {
                        string path = item.Tag as string;
                        if (selection.Contains(path) || (string.Compare(_pathToSelect, path, true) == 0))
                        {
                            if (!focusSet)
                            {
                                item.Focused = true;
                                focusSet     = true;
                            }

                            item.Selected = true;
                            EnsureVisible(item.Index);
                            selectedSomething = true;
                        }
                    }
                }
            }
            else if (m_strPrevDirPath != null && m_strPrevDirPath.Length > 0)
            {
                int lastVisibleIndex = 0;
                foreach (ListViewItem item in this.Items)
                {
                    string path = item.Tag as string;
                    if (string.IsNullOrEmpty(path) == false)
                    {
                        item.Selected = false;

                        if (string.Compare(path, m_strPrevDirPath, false) == 0)
                        {
                            item.Selected = true;
                            item.Focused  = true;

                            lastVisibleIndex = item.Index;

                            break;
                        }
                    }
                }

                EnsureVisible(lastVisibleIndex);
                selectedSomething = true;
            }

            if (!selectedSomething)
            {
                if (selIdx < 0)
                {
                    selIdx = 0;
                }
                if (selIdx >= this.Items.Count)
                {
                    selIdx = this.Items.Count - 1;
                }

                this.Items[selIdx].Selected = true;
                this.Items[selIdx].Focused  = true;
                EnsureVisible(selIdx);
            }

            this.Select();
            this.Focus();
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            string        checksumfile = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location).Directory.FullName;
            string        output       = checksumfile + "\\Deletable_" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".txt";
            List <string> locations    = new List <string>();// ConfigurationManager.AppSettings.AllKeys.ToList();
            List <string> excludes     = ConfigurationManager.AppSettings["Exclude"].Split(';').ToList();

            excludes.RemoveAll(item => string.IsNullOrEmpty(item));
            ShareCollection shi;

            switch (Convert.ToBoolean(string.IsNullOrEmpty(ConfigurationManager.AppSettings["GetLocal"]) ? "false" : ConfigurationManager.AppSettings["GetLocal"]))
            {
            case true:
                shi = ShareCollection.LocalShares;
                break;

            case false:
            default:
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["NAS"]))
                {
                    shi = ShareCollection.GetShares(ConfigurationManager.AppSettings["NAS"]);
                }
                else
                {
                    Console.WriteLine("Invalid setting found in app.config, program terminated.");
                    return;
                }
                break;
            }
            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    Console.WriteLine("{0}: {1} [{2}]",
                                      si.ShareType, si, si.Path);
                    if (si.ShareType == ShareType.Disk)
                    {
                        locations.Add(si.ToString().Replace(@"\\", @"\"));
                    }
                    // If this is a file-system share, try to
                    // list the first five subfolders.
                    // NB: If the share is on a removable device,
                    // you could get "Not ready" or "Access denied"
                    // exceptions.
                    //if (si.IsFileSystem)
                    //{
                    //    try
                    //    {
                    //        DirectoryInfo d = si.Root;
                    //        DirectoryInfo[] Flds = d.GetDirectories();
                    //        //for (int i = 0; i < Flds.Length && i < 5; i++)
                    //        //    Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);

                    //        //Console.WriteLine();
                    //    }
                    //    catch (Exception)
                    //    {
                    //        //Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                    //        //    si, ex.Message);
                    //    }
                    //}
                }
            }
            else
            {
                Console.WriteLine("Unable to enumerate the local shares.");
            }


            //locations.Add(@"\\Diskstation\photo\");

            int           deletable = 0;
            List <string> FileList  = null;

            using (StreamWriter file = File.CreateText(output))
            { }
            foreach (var loc in locations)
            {
                Console.WriteLine("Scanning " + loc);
                FileList = GetFiles(loc, "*.*");
                if (FileList != null)
                {
                    if (FileList.Count != 0)
                    {
                        Console.WriteLine(FileList.Count + " files could be deleted by current user account");
                    }
                }
                if (FileList.Any())
                {
                    using (StreamWriter file = File.AppendText(output))
                    {
                        foreach (var fi in FileList)
                        {
                            file.WriteLine(fi);
                        }
                    }
                    deletable += FileList.Count;
                }
            }
            if (FileList != null)
            {
                Console.WriteLine("Total : " + deletable + " files could be deleted by current user account.");
            }
            Console.WriteLine("Finished");
            Console.ReadKey();
        }
Beispiel #26
0
        private void backgroundWorker2_netscanner_DoWork(object sender, DoWorkEventArgs ev)
        {
            Program.netscan_in_progress = true;

            /*
             *      var nb = new NetworkBrowser();
             *      var doms = nb.GetNetworkDomains();
             *      //doms.Add("WORKGROUP");
             *      foreach (var domain in doms)
             *      {
             *              var comps = nb.GetNetworkComputers(domain);
             *              foreach (var computer in comps)
             *              {
             *                      var sc = new ShareCollection();
             *                      ShareCollection shares = ShareCollection.GetShares("\\\\" + computer); // no domain used here. computers need to be unique!?!?
             *                      foreach (Share share in shares) if (share.IsFileSystem && share.ShareType == ShareType.Disk)
             *                              {
             *                                      var drive = new NetworkDrive(share);
             *                                      Program.visibleNetworkDrives.Add(drive); //new Drive "\\\\" + computer + "\\" + share.NetName + " (" + share.Remark + ")"
             *                                      backgroundWorker2_netscanner.ReportProgress(50);
             *                              }
             *              }
             *      }
             */

            // approach #2: ServerEnum
            ServerEnum shares = new ServerEnum(ResourceScope.RESOURCE_GLOBALNET,
                                               ResourceType.RESOURCETYPE_DISK,
                                               ResourceUsage.RESOURCEUSAGE_ALL,
                                               ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE);
            List <Share> foundshares = new List <Share>();

            foreach (string servershare in Program.additional_netshares)
            {
                string[] split = servershare.Split(new char[1] {
                    '\\'
                });
                try {
                    Share share = ShareCollection.GetNetShareInfo(split[2], split[3]);
                    add_unique_share(foundshares, share);
                }
                catch (Exception e) {
                }
            }

            foreach (string servershare in shares)
            {
                string[] split = servershare.Split(new char[1] {
                    '\\'
                });
                try {
                    Share share = ShareCollection.GetNetShareInfo(split[2], split[3]);
                    add_unique_share(foundshares, share);
                }
                catch (Exception e) {
                }
            }

            lock (Program.visibleNetworkDrives) {
                Program.visibleNetworkDrives.Clear();

                foreach (Share share in foundshares)
                {
                    var drive = new NetworkDrive(share);
                    Program.visibleNetworkDrives.Add(drive);                     //new Drive "\\\\" + computer + "\\" + share.NetName + " (" + share.Remark + ")"
                }

                Program.netscan_in_progress = false;
            }
        }
Beispiel #27
0
            /// <summary>
            /// Enumerates the shares
            /// </summary>
            /// <param name="server">The server name</param>
            /// <param name="shares">The ShareCollection</param>
            protected static void EnumerateShares(string server, ShareCollection shares)
            {
                if (null != server && 0 != server.Length && !IsW2KUp)
                {
                    server = server.ToUpper();

                    // On NT4, 9x and Me, server has to start with "\\"
                    if (!('\\' == server[0] && '\\' == server[1]))
                        server = @"\\" + server;
                }

                if (IsNT)
                    EnumerateSharesNT(server, shares);
                else
                    EnumerateShares9x(server, shares);
            }
Beispiel #28
0
        private void FillComments(ShareCollection shares, SqlQuery query)
        {
            if (shares.Count == 0)
                return;

            List<int> minIds = new List<int>();
            List<int> maxIds = new List<int>();

            for (int i = 0; i < shares.Count; i++)
            {
                if (shares[i].TotalComments == 0)
                    continue;
                else if (shares[i].TotalComments == 1)
                    minIds.Add(shares[i].UserShareID);
                else
                {
                    minIds.Add(shares[i].UserShareID);
                    maxIds.Add(shares[i].UserShareID);
                }
            }

            if (minIds.Count == 0)
                return;

            query.Parameters.Clear();
            query.CommandType = CommandType.Text;

            query.CommandText = @"
SELECT * FROM bx_Comments WHERE CommentID IN(
    SELECT Min(CommentID) FROM [bx_Comments] WHERE [Type]=5 AND IsApproved = 1 AND [TargetID] IN(@MinTargetIDs) GROUP BY TargetID
)
";
            if (maxIds.Count > 0)
            {
                query.CommandText += @"
 UNION 
SELECT * FROM bx_Comments WHERE CommentID IN(
    SELECT Max(CommentID) FROM [bx_Comments] WHERE [Type]=5 AND IsApproved = 1 AND [TargetID] IN(@MaxTargetIDs) GROUP BY TargetID
)
";
            }

            query.CreateInParameter<int>("@MinTargetIDs", minIds);
            query.CreateInParameter<int>("@MaxTargetIDs", maxIds);

            Share share = null;

            using (XSqlDataReader reader = query.ExecuteReader())
            {
                while (reader.Read())
                {
                    Comment comment = new Comment(reader);

                    if (share == null || share.UserShareID!=comment.TargetID)
                    {
                        foreach (Share tempShare in shares)
                        {
                            if (tempShare.UserShareID == comment.TargetID)
                            {
                                share = tempShare;
                                break;
                            }
                        }
                    }
                    if (share != null)
                    {
                        if (share.CommentList.ContainsKey(comment.CommentID) == false)
                            share.CommentList.Add(comment);
                    }
                }
            }
        }
Beispiel #29
0
		public override ShareCollection GetFriendShares(int userID, ShareType? shareType, int pageNumber, int pageSize)
		{
			using (SqlQuery query = new SqlQuery())
			{
                query.Pager.TableName = "[bx_SharesView]";
				query.Pager.SortField = "ShareID";
				query.Pager.PageNumber = pageNumber;
				query.Pager.PageSize = pageSize;
				query.Pager.IsDesc = true;
				query.Pager.SelectCount = true;

                StringBuilder sql = new StringBuilder();
				if (shareType.HasValue&& shareType.Value != ShareType.All)
				{
                    sql.Append(" [Type] = @Type AND ");

					query.CreateParameter<ShareType>("@Type", shareType.Value, SqlDbType.TinyInt);
				}

                sql.Append(" [UserID2] IN (SELECT [FriendUserID] FROM [bx_Friends] WHERE [UserID] = @UserID) AND ([PrivacyType] IN (0,1,3)) ");
				query.Pager.Condition = sql.ToString();

				query.CreateParameter<int>("@UserID", userID, SqlDbType.Int);

                ShareCollection shares;
				using (XSqlDataReader reader = query.ExecuteReader())
				{
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
					{
                        if (reader.Read())
						{
                            shares.TotalRecords = reader.Get<int>(0);
						}
                    }
                }
                FillComments(shares, query);
                return shares;
			}
		}
Beispiel #30
0
        public bgrCSP(string [] args)
        {
            int nshared = 0; // counter for number of shared files

            if (args.Length == 0)
            {
                MessageBox.Show("ovaj program se koristi tako što prevučeš jedan ili\r\nviše fajlova/foldera na ikonicu koju si upravo kliknuo\r\n\r\nza više informacija pogledaj uputstvo", "bgrCopySharePath " + version, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }

            else
            {
                string all = string.Empty;
                for (int i = 0; i < args.Length; i++)
                {
                    string temp = ShareCollection.PathToUnc(args[i]);
                    if (temp.StartsWith("\\"))
                    {
                        all += "[URL]" + temp + "[/URL]\r\n";
                        nshared++;
                    }
                }

                if (all == string.Empty)
                {
                    MessageBox.Show("fajlovi su iz foldera koji NIJE SHAREOVAN\r\n\r\nshareuj folder pa probaj opet\r\nili stavi fajlove u neki već shareovan folder", "greška", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    if (nshared < args.Length)
                    {
                        string srpskaGramatika;
                        int    notshared = args.Length - nshared;
                        if (notshared % 10 == 1 && notshared != 11)
                        {
                            srpskaGramatika = "izabran fajl nije shareovan";
                        }
                        else if ((notshared % 10 == 2 || notshared % 10 == 3 || notshared % 10 == 4) && (notshared != 12 && notshared != 13 && notshared != 14))
                        {
                            srpskaGramatika = "izabrana fajla nisu shareovana";
                        }
                        else
                        {
                            srpskaGramatika = "izabranih fajlova nije shareovano";
                        }
                        MessageBox.Show(notshared + " od " + args.Length + " " + srpskaGramatika + "\r\n\r\npreostalih " + nshared + " su pripremljeni za pasteovanje", "poruka", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    try
                    {
                        all = "[QUOTE]\r\n" + all + "[/QUOTE]";

                        //Clipboard.SetText(all);

                        //Clipboard.Clear();
                        //Clipboard.SetDataObject(all, true, 6, 250);

                        TextBox tb = new TextBox();
                        tb.Text = all;
                        tb.SelectAll();
                        tb.Copy();
                        //MessageBox.Show(tb.Text);
                        SystemSounds.Beep.Play();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Došlo je do greške. Zapiši ili izvadi screenshot i daj bugeru\r\n\r\n" + e.ToString() + "\r\n" + e.Message, "obavesti bugera", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
            string message = checkForUpdate();

            if (message != "OK")
            {
                MessageBox.Show("Došlo je do sledeće greške u pokušaju update-a:\r\n\r\n\"" + message + "\"\r\n\r\nzapamti tekst greške i javi bugeru", "greška", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
Beispiel #31
0
        public override ShareCollection GetHotShares(ShareType? shareType, DateTime? beginDate, HotShareSortType sortType, int pageNumber, int pageSize, out int totalCount)
        {
            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.TableName = "[bx_SharesView]";
                query.Pager.PrimaryKey = "[UserShareID]";
                if (sortType == HotShareSortType.ShareCount)
                    query.Pager.SortField = "ShareCount";
                else
                    query.Pager.SortField = " [AgreeAndOpposeCount] ";
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                query.Pager.IsDesc = true;
                query.Pager.SelectCount = true;

                StringBuilder sql = new StringBuilder(" UserShareID IN(SELECT MIN(UserShareID) FROM bx_SharesView WHERE ");
                if (shareType.HasValue && shareType.Value != ShareType.All)
                {
                    sql.Append(" [Type] = @Type AND ");

                    query.CreateParameter<ShareType>("@Type", shareType.Value, SqlDbType.TinyInt);
                }

                if (beginDate != null)
                {
                    sql.Append(" [CreateDate] >= @BeginDate AND ");
                    query.CreateParameter<DateTime>("@BeginDate", beginDate.Value, SqlDbType.DateTime);
                }

                sql.Append(" [PrivacyType] = 0 GROUP BY ShareID) ");
                query.Pager.Condition = sql.ToString();

                ShareCollection shares;
                totalCount = 0;
                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
                    {
                        if (reader.Read())
                        {
                            totalCount = reader.Get<int>(0);
                        }
                    }
                }
                FillComments(shares, query);
                return shares;
            }
        }
Beispiel #32
0
        public override ShareCollection SearchShares(int pageNumber, ShareFilter filter, IEnumerable<Guid>  excludeRoleIDs, ref int totalCount)
        {

            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.IsDesc = filter.IsDesc;

                if (filter.Order == ShareFilter.OrderBy.ShareID)
                    query.Pager.SortField = filter.Order.ToString();

                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = filter.PageSize;
                query.Pager.TotalRecords = totalCount;
                query.Pager.SelectCount = true;
                query.Pager.TableName = "[bx_SharesView]";

                SqlConditionBuilder condition = new SqlConditionBuilder(SqlConditionStart.None);
                condition += (filter.UserID == null ? "" : ("AND [UserID] = @UserID "));
                condition += (filter.ShareID == null ? "" : ("AND [ShareID] = @ShareID "));
                condition += (filter.ShareType == ShareType.All ? "" : ("AND [Type] = @Type "));
                condition += (filter.PrivacyType == null ? "" : ("AND [PrivacyType] = @PrivacyType "));
                condition += (filter.BeginDate == null ? "" : ("AND [CreateDate] > @BeginDate "));
                condition += (filter.EndDate == null ? "" : ("AND [CreateDate] < @EndDate "));
                condition.AppendAnd(DaoUtil.GetExcludeRoleSQL("[UserID]", excludeRoleIDs, query));

                query.Pager.Condition = condition.ToString();



                query.CreateParameter<int?>("@UserID", filter.UserID, SqlDbType.Int);
                query.CreateParameter<int?>("@ShareID", filter.ShareID, SqlDbType.Int);
                query.CreateParameter<int>("@Type", (int)filter.ShareType, SqlDbType.Int);
                query.CreateParameter<int?>("@PrivacyType", filter.PrivacyType == null ? 0 : (int)filter.PrivacyType, SqlDbType.Int);
                query.CreateParameter<DateTime?>("@BeginDate", filter.BeginDate, SqlDbType.DateTime);
                query.CreateParameter<DateTime?>("@EndDate", filter.EndDate, SqlDbType.DateTime);



                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    ShareCollection shares = new ShareCollection(reader);

                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            totalCount = reader.Get<int>(0);
                        }
                    }
                    return shares;
                }
            }
        }
Beispiel #33
0
            /// <summary>
            /// Enumerates the shares on Windows NT
            /// </summary>
            /// <param name="server">The server name</param>
            /// <param name="shares">The ShareCollection</param>
            protected static void EnumerateSharesNT(string server, ShareCollection shares)
            {
                int level = 2;
                int entriesRead, totalEntries, nRet, hResume = 0;
                IntPtr pBuffer = IntPtr.Zero;

                try
                {
                    nRet = NetShareEnum(server, level, out pBuffer, -1,
                        out entriesRead, out totalEntries, ref hResume);

                    if (ERROR_ACCESS_DENIED == nRet)
                    {
                        //Need admin for level 2, drop to level 1
                        level = 1;
                        nRet = NetShareEnum(server, level, out pBuffer, -1,
                            out entriesRead, out totalEntries, ref hResume);
                    }

                    if (NO_ERROR == nRet && entriesRead > 0)
                    {
                        Type t = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1);
                        int offset = Marshal.SizeOf(t);

                        for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += offset)
                        {
                            IntPtr pItem = new IntPtr(lpItem);
                            if (1 == level)
                            {
                                SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                            }
                            else
                            {
                                SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                            }
                        }
                    }

                }
                finally
                {
                    // Clean up buffer allocated by system
                    if (IntPtr.Zero != pBuffer)
                        NetApiBufferFree(pBuffer);
                }
            }
Beispiel #34
0
        private void banana()
        {
            string filePath = textBox1.Text;

            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }


            if (!File.Exists(filePath))
            {
                MessageBox.Show("File not found:\n\n" + filePath, "File not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            FileInfo fileInfo = new FileInfo(filePath);

            string uncPath = Extensions.UncPath(fileInfo);

            if (string.IsNullOrEmpty(uncPath))
            {
                MessageBox.Show("Error getting UNC path for:\n\n" + filePath, "Bad UNC", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }


            ListView1.Items.Clear();
            listFileInfo.Clear();

            string remoteFileName = ShareCollection.UncPathToRemoteFilePath(uncPath);

            if (!string.IsNullOrEmpty(remoteFileName))
            {
                string server = GetServerNameFromUNC(uncPath);
                FileEnum(remoteFileName, server);
            }
            else
            {
                MessageBox.Show("Error getting remote file name", "Remote file name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (listFileInfo.Count > 0)
            {
                int i = 0;
                foreach (FileLockInfo info in listFileInfo)
                {
                    ListViewItem lvi = new ListViewItem(info.remotePath);
                    lvi.SubItems.Add(info.userName);
                    lvi.SubItems.Add(info.numberOfLocks.ToString());
                    lvi.SubItems.Add(info.permissions);
                    lvi.SubItems.Add(uncPath);
                    lvi.SubItems.Add(info.id.ToString());

                    ListView1.Items.Add(lvi);
                }

                ColorLines(ListView1, false);
            }
        }
Beispiel #35
0
            /// <summary>
            /// Enumerates the shares on Windows 9x
            /// </summary>
            /// <param name="server">The server name</param>
            /// <param name="shares">The ShareCollection</param>
            protected static void EnumerateShares9x(string server, ShareCollection shares)
            {
                int level = 50;
                int nRet = 0;
                ushort entriesRead, totalEntries;

                Type t = typeof(SHARE_INFO_50);
                int size = Marshal.SizeOf(t);
                ushort cbBuffer = (ushort)(MAX_SI50_ENTRIES * size);
                //On Win9x, must allocate buffer before calling API
                IntPtr pBuffer = Marshal.AllocHGlobal(cbBuffer);

                try
                {
                    nRet = NetShareEnum(server, level, pBuffer, cbBuffer,
                        out entriesRead, out totalEntries);

                    if (ERROR_WRONG_LEVEL == nRet)
                    {
                        level = 1;
                        t = typeof(SHARE_INFO_1_9x);
                        size = Marshal.SizeOf(t);

                        nRet = NetShareEnum(server, level, pBuffer, cbBuffer,
                            out entriesRead, out totalEntries);
                    }

                    if (NO_ERROR == nRet || ERROR_MORE_DATA == nRet)
                    {
                        for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += size)
                        {
                            IntPtr pItem = new IntPtr(lpItem);

                            if (1 == level)
                            {
                                SHARE_INFO_1_9x si = (SHARE_INFO_1_9x)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                            }
                            else
                            {
                                SHARE_INFO_50 si = (SHARE_INFO_50)Marshal.PtrToStructure(pItem, t);
                                shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                            }
                        }
                    }
                    else
                        Console.WriteLine(nRet);

                }
                finally
                {
                    //Clean up buffer
                    Marshal.FreeHGlobal(pBuffer);
                }
            }
Beispiel #36
0
        public override ShareCollection GetCommentedSharesOrderByRank(int userID, ShareType? shareType, int pageSize, int pageNumber)
        {
            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.TableName = "[bx_SharesView]";
                query.Pager.PrimaryKey = "[UserShareID]";
                query.Pager.SortField = "[UserShareID]";
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                query.Pager.IsDesc = true;
                query.Pager.SelectCount = true;

                query.Pager.Condition = "";

                if (shareType.HasValue && shareType.Value != ShareType.All)
                {
                    query.Pager.Condition = "[Type] = @Type AND ";

                    query.CreateParameter<ShareType>("@Type", shareType.Value, SqlDbType.TinyInt);
                }

                query.Pager.Condition =  query.Pager.Condition + " [UserShareID] IN (SELECT [TargetID] FROM [bx_Comments] WHERE [Type]=5 AND [UserID] = @UserID AND IsApproved = 1)";

                query.CreateParameter<int>("@UserID", userID, SqlDbType.Int);

                ShareCollection shares;
                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
                    {
                        if (reader.Read())
                        {
                            shares.TotalRecords = reader.Get<int>(0);
                        }
                    }

                }

                FillComments(shares, query);
                return shares;
            }
        }
Beispiel #37
0
        /// <summary>
        /// Scan the client machine for services such as HTTP or samba shares
        /// </summary>
        /// <param name="n"></param>
        private void ScanClient(Node n)
        {
            //Check for HTTP
            string webTitle = string.Empty;

            try
            {
                var    wc   = new WebClient();
                string html = wc.DownloadString("http://" + n.Host);

                if (!string.IsNullOrEmpty(html))
                {
                    webTitle = RegexEx.FindMatches("<title>.*</title>", html).FirstOrDefault();
                    if (null != webTitle && !string.IsNullOrEmpty(html) && webTitle.Length > 14)
                    {
                        webTitle = webTitle.Substring(7);
                        webTitle = webTitle.Substring(0, webTitle.Length - 8);
                    }
                }

                if (string.IsNullOrEmpty(webTitle))
                {
                    webTitle = "Web";
                }
            }
            catch
            {
            }

            //Check for FTP
            string ftp = string.Empty;

            try
            {
                var client = new TcpClient();
                client.Connect(n.Host, 21);
                ftp = "FTP";
                var  sb    = new StringBuilder();
                long start = Environment.TickCount + 3000;
                var  data  = new byte[20000];
                client.ReceiveBufferSize = data.Length;

                while (start > Environment.TickCount && client.Connected)
                {
                    if (client.GetStream().DataAvailable)
                    {
                        int length = client.GetStream().Read(data, 0, data.Length);
                        sb.Append(Encoding.ASCII.GetString(data, 0, length));
                    }
                    else
                    {
                        Thread.Sleep(50);
                    }
                }
                client.Close();

                string title = sb.ToString();
                if (!string.IsNullOrEmpty(title))
                {
                    ftp = title;
                }
                data = null;
            }
            catch
            {
            }

            //Check for samba shares

            string samba = string.Empty;

            try
            {
                ShareCollection shares = ShareCollection.GetShares(n.Host);
                var             sb     = new StringBuilder();
                foreach (SambaShare share in shares)
                {
                    if (share.IsFileSystem && share.ShareType == ShareType.Disk)
                    {
                        try
                        {
                            //Make sure its readable
                            DirectoryInfo[] Flds = share.Root.GetDirectories();
                            if (sb.Length > 0)
                            {
                                sb.Append("|");
                            }
                            sb.Append(share.NetName);
                        }
                        catch
                        {
                        }
                    }
                }
                samba = sb.ToString();
            }
            catch
            {
            }

            lock (sync)
            {
                //update clients and overlords
                var r = new Node();
                r.SetData("HTTP", webTitle.Replace("\n", "").Replace("\r", ""));
                r.SetData("FTP", ftp.Replace("\n", "").Replace("\r", ""));
                r.SetData("Shares", samba.Replace("\n", "").Replace("\r", ""));
                r.ID         = n.ID;
                r.OverlordID = serverNode.ID;
                lock (sync)
                {
                    //Check the client is still connected..
                    if (connectedClientNodes.Where(nx => nx.Node.ID == r.ID).Count() > 0)
                    {
                        var verb = new UpdateVerb();
                        verb.Nodes.Add(r);
                        NetworkRequest req = verb.CreateRequest();
                        req.OverlordID = serverNode.ID;
                        SendToStandardClients(req);
                        //Dont updates about overlords to other overlords
                        if (n.NodeType != ClientType.Overlord)
                        {
                            SendToOverlordClients(req);
                        }
                    }
                }
                //Store info
                n.SetData("HTTP", webTitle.Replace("\n", "").Replace("\r", ""));
                n.SetData("FTP", ftp.Replace("\n", "").Replace("\r", ""));
                n.SetData("Shares", samba.Replace("\n", "").Replace("\r", ""));
            }
        }
Beispiel #38
0
        public override ShareCollection GetEveryoneSharesOrderByRank(ShareType? shareType, DateTime? beginDate, int pageSize, int pageNumber)
        {
            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.TableName = "[bx_SharesView]";
                query.Pager.PrimaryKey = "[UserShareID]";
                query.Pager.SortField = "[UserShareID]";
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                query.Pager.IsDesc = true;
                query.Pager.SelectCount = true;

                if (shareType.HasValue && shareType.Value != ShareType.All)
                {
                    query.Pager.Condition = "[Type] = @Type AND ";

                    query.CreateParameter<ShareType>("@Type", shareType.Value, SqlDbType.TinyInt);
                }

                if (beginDate.HasValue)
                {
                    query.Pager.Condition = "[CreateDate] >= @BeginDate AND ";

                    query.CreateParameter<DateTime>("@BeginDate", beginDate.Value, SqlDbType.DateTime);
                }

                query.Pager.Condition = " ([PrivacyType] IN (0,3))";

                ShareCollection shares;
                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
                    {
                        if (reader.Read())
                        {
                            shares.TotalRecords = reader.Get<int>(0);
                        }
                    }

                }
                FillComments(shares, query);
                return shares;
            }
        }
Beispiel #39
0
    //static void Main(string[] args)
    //{
    //	TestShares();
    //}

    static void TestShares()
    {
        // Enumerate shares on local computer
        Console.WriteLine("\nShares on local computer:");
        ShareCollection shi = ShareCollection.LocalShares;

        if (shi != null)
        {
            foreach (Share si in shi)
            {
                Console.WriteLine("{0}: {1} [{2}]",
                                  si.ShareType, si, si.Path);

                // If this is a file-system share, try to
                // list the first five subfolders.
                // NB: If the share is on a removable device,
                // you could get "Not ready" or "Access denied"
                // exceptions.
                if (si.IsFileSystem)
                {
                    try
                    {
                        DirectoryInfo   d    = si.Root;
                        DirectoryInfo[] Flds = d.GetDirectories();
                        for (int i = 0; i < Flds.Length && i < 5; i++)
                        {
                            Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);
                        }

                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                                          si, ex.Message);
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("Unable to enumerate the local shares.");
        }

        Console.WriteLine();

        // Enumerate shares on a remote computer
        Console.Write("Enter the NetBios name of a server on your network: ");
        string server = Console.ReadLine();

        if (server != null && server.Trim().Length > 0)
        {
            Console.WriteLine("\nShares on {0}:", server);
            shi = ShareCollection.GetShares(server);
            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    Console.WriteLine("{0}: {1} [{2}]", si.ShareType, si, si.Path);

                    // If this is a file-system share, try to
                    // list the first five subfolders.
                    // NB: If the share is on a removable device,
                    // you could get "Not ready" or "Access denied"
                    // exceptions.
                    // If you don't have permissions to the share,
                    // you will get security exceptions.
                    if (si.IsFileSystem)
                    {
                        try
                        {
                            System.IO.DirectoryInfo   d    = si.Root;
                            System.IO.DirectoryInfo[] Flds = d.GetDirectories();
                            for (int i = 0; i < Flds.Length && i < 5; i++)
                            {
                                Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);
                            }

                            Console.WriteLine();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                                              si.ToString(), ex.Message);
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("Unable to enumerate the shares on {0}.\n"
                                  + "Make sure the machine exists, and that you have permission to access it.",
                                  server);
            }

            Console.WriteLine();
        }

        // Resolve local paths to UNC paths.
        string fileName = string.Empty;

        do
        {
            Console.Write("Enter the path to a file, or \"Q\" to exit: ");
            fileName = Console.ReadLine();
            if (fileName != null && fileName.Length > 0)
            {
                if (fileName.ToUpper() == "Q")
                {
                    fileName = string.Empty;
                }
                else
                {
                    Console.WriteLine("{0} = {1}", fileName, ShareCollection.PathToUnc(fileName));
                }
            }
        } while (fileName != null && fileName.Length > 0);
    }
Beispiel #40
0
        public override ShareCollection GetFriendShares(int userID, ShareType shareType, int pageNumber, int pageSize, out int totalCount)
        {
            totalCount = 0;
            using (SqlQuery query = new SqlQuery())
            {
                StringBuffer conditions = new StringBuffer();

                conditions += "UserID IN (@UserIDs)";
                query.CreateParameter<int>("@UserID", userID, SqlDbType.Int);

                if (shareType != ShareType.All)
                {
                    conditions += " AND [Type] = @ShareType";
                    query.CreateParameter<int>("@ShareType", (int)shareType, SqlDbType.TinyInt);
                }

                conditions += " AND [PrivacyType] < 2";

                query.Pager.IsDesc = true;
                query.Pager.SortField = "UserShareID";
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                //query.Pager.TotalRecords = totalCount;
                query.Pager.SelectCount = true;
                query.Pager.TableName = "[bx_SharesView]";
                query.Pager.Condition = conditions.ToString();

                ShareCollection shares;
                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            totalCount = reader.Get<int>(0);
                        }
                    }
                }
                FillComments(shares, query);
                return shares;
            }
        }
Beispiel #41
0
        public override DenouncingCollection GetDenouncingWithShare(DenouncingFilter filter, int pageNumber)
        {
            using (SqlSession db = new SqlSession())
            {
                DenouncingCollection denouncings = null;

                using (SqlQuery query = db.CreateQuery())
                {
                    query.Pager.PageNumber = pageNumber;
                    query.Pager.PageSize = filter.PageSize;
                    query.Pager.TableName = "bx_Denouncings";
                    query.Pager.SortField = "DenouncingID";
                    query.Pager.IsDesc = filter.IsDesc;
                    query.Pager.SelectCount = true;

                    filter.Type = DenouncingType.Share;

                    GetSearchDenouncingsCondition(query, filter);

                    using (XSqlDataReader reader = query.ExecuteReader())
                    {
                        denouncings = new DenouncingCollection(reader);

                        if (reader.NextResult())
                        {
                            while (reader.Read())
                                denouncings.TotalRecords = reader.Get<int>(0);
                        }
                    }
                }

                FillDenouncingContents(denouncings, db);

                if (denouncings.Count > 0)
                {
                    int[] targetIDs = GetTargetIDs(denouncings);

                    ShareCollection shares = null;

                    using (SqlQuery query = db.CreateQuery())
                    {
                        query.CommandText = "SELECT * FROM bx_SharesView WHERE ShareID IN (@IDs)";

                        query.CreateInParameter<int>("@IDs", targetIDs);

                        using (XSqlDataReader reader = query.ExecuteReader())
                        {
                            shares = new ShareCollection(reader);
                        }
                    }

                    ShareBO.Instance.ProcessKeyword(shares, ProcessKeywordMode.FillOriginalText);

                    for (int i = 0; i < denouncings.Count; i++)
                    {
                        for (int j = 0; j < shares.Count; j++)
                        {
                            if (denouncings[i].TargetID == shares[j].ShareID)
                            {
                                denouncings[i].TargetShare = shares[j];
                                break;
                            }
                        }
                    }
                }
                return denouncings;
            }
        }
Beispiel #42
0
		public override ShareCollection GetEveryoneShares(ShareType? shareType, int pageNumber, int pageSize, ref int? totalCount)
		{
			using (SqlQuery query = new SqlQuery())
			{
                query.Pager.TableName = "[bx_SharesView]";
				query.Pager.SortField = "[ShareID]";
				query.Pager.PageNumber = pageNumber;
				query.Pager.PageSize = pageSize;
				query.Pager.TotalRecords = totalCount;
				query.Pager.IsDesc = true;
				query.Pager.SelectCount = true;

                StringBuilder sql = new StringBuilder(" UserShareID IN(SELECT MIN(UserShareID) FROM bx_SharesView WHERE");
				if (shareType.HasValue && shareType.Value != ShareType.All)
				{
                    sql.Append(" [Type] = @Type AND ");

					query.CreateParameter<ShareType>("@Type", shareType.Value, SqlDbType.TinyInt);
				}
                sql.Append(" [PrivacyType] = 0  GROUP BY ShareID) ");

                query.Pager.Condition = sql.ToString();

                ShareCollection shares;
				using (XSqlDataReader reader = query.ExecuteReader())
				{
                    shares = new ShareCollection(reader);

                    if (totalCount == null && reader.NextResult())
					{
                        if (reader.Read())
						{
                            totalCount = reader.Get<int>(0);
						}
					}

					shares.TotalRecords = totalCount.GetValueOrDefault();

				}
                FillComments(shares, query);
				return shares;
			}
		}
Beispiel #43
0
            /// <summary>
            /// Returns the UNC path for a mapped drive or local share.
            /// </summary>
            /// <param name="fileName">The path to map</param>
            /// <returns>The UNC path (if available)</returns>
            public static string PathToUnc(string fileName)
            {
                if (null == fileName || 0 == fileName.Length)
                {
                    return(string.Empty);
                }

                fileName = Path.GetFullPath(fileName);
                if (!IsValidFilePath(fileName))
                {
                    return(fileName);
                }

                int nRet = 0;
                UNIVERSAL_NAME_INFO rni = new UNIVERSAL_NAME_INFO();
                int bufferSize          = Marshal.SizeOf(rni);

                nRet = WNetGetUniversalName(
                    fileName, UNIVERSAL_NAME_INFO_LEVEL,
                    ref rni, ref bufferSize);

                if (ERROR_MORE_DATA == nRet)
                {
                    IntPtr pBuffer = Marshal.AllocHGlobal(bufferSize);;
                    try
                    {
                        nRet = WNetGetUniversalName(
                            fileName, UNIVERSAL_NAME_INFO_LEVEL,
                            pBuffer, ref bufferSize);

                        if (NO_ERROR == nRet)
                        {
                            rni = (UNIVERSAL_NAME_INFO)Marshal.PtrToStructure(pBuffer,
                                                                              typeof(UNIVERSAL_NAME_INFO));
                        }
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(pBuffer);
                    }
                }

                switch (nRet)
                {
                case NO_ERROR:
                    return(rni.lpUniversalName);

                case ERROR_NOT_CONNECTED:
                    //Local file-name
                    ShareCollection shi = LocalShares;
                    if (null != shi)
                    {
                        Share share = shi[fileName];
                        if (null != share)
                        {
                            string path = share.Path;
                            if (null != path && 0 != path.Length)
                            {
                                int index = path.Length;
                                if (Path.DirectorySeparatorChar != path[path.Length - 1])
                                {
                                    index++;
                                }

                                if (index < fileName.Length)
                                {
                                    fileName = fileName.Substring(index);
                                }
                                else
                                {
                                    fileName = string.Empty;
                                }

                                fileName = Path.Combine(share.ToString(), fileName);
                            }
                        }
                    }

                    return(fileName);

                default:
                    Console.WriteLine("Unknown return value: {0}", nRet);
                    return(string.Empty);
                }
            }
Beispiel #44
0
        public override ShareCollection GetUserCommentedShares(int userID, ShareType? shareType, int pageNumber, int pageSize)
        {
            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.TableName = "[bx_SharesView]";
                query.Pager.SortField = "UserShareID";
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                query.Pager.IsDesc = true;
                query.Pager.SelectCount = true;
                query.Pager.Condition = "[UserShareID] IN (SELECT [TargetID] FROM [bx_Comments] WHERE [Type]=5 AND [UserID] = @UserID AND IsApproved = 1)";

                if (shareType != null && shareType != ShareType.All)
                {
                    query.Pager.Condition += " AND [Type] = @ShareType";
                    query.CreateParameter<int>("@ShareType", (int)shareType, SqlDbType.TinyInt);
                }

                query.Pager.Condition += " AND [PrivacyType] < 2";

                query.CreateParameter<int>("@UserID", userID, SqlDbType.Int);

                ShareCollection shares;
                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    shares = new ShareCollection(reader);

                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            shares.TotalRecords = reader.Get<int>(0);
                        }
                    }
                }
                FillComments(shares, query);
                return shares;
            }
        }
Beispiel #45
0
        public override DenouncingCollection GetDenouncingWithShare(DenouncingFilter filter, int pageNumber)
        {
            using (SqlSession db = new SqlSession())
            {
                DenouncingCollection denouncings = null;

                using (SqlQuery query = db.CreateQuery())
                {
                    query.Pager.PageNumber  = pageNumber;
                    query.Pager.PageSize    = filter.PageSize;
                    query.Pager.TableName   = "bx_Denouncings";
                    query.Pager.SortField   = "DenouncingID";
                    query.Pager.IsDesc      = filter.IsDesc;
                    query.Pager.SelectCount = true;

                    filter.Type = DenouncingType.Share;

                    GetSearchDenouncingsCondition(query, filter);

                    using (XSqlDataReader reader = query.ExecuteReader())
                    {
                        denouncings = new DenouncingCollection(reader);

                        if (reader.NextResult())
                        {
                            while (reader.Read())
                            {
                                denouncings.TotalRecords = reader.Get <int>(0);
                            }
                        }
                    }
                }

                FillDenouncingContents(denouncings, db);

                if (denouncings.Count > 0)
                {
                    int[] targetIDs = GetTargetIDs(denouncings);

                    ShareCollection shares = null;

                    using (SqlQuery query = db.CreateQuery())
                    {
                        query.CommandText = "SELECT * FROM bx_SharesView WHERE ShareID IN (@IDs)";

                        query.CreateInParameter <int>("@IDs", targetIDs);

                        using (XSqlDataReader reader = query.ExecuteReader())
                        {
                            shares = new ShareCollection(reader);
                        }
                    }

                    ShareBO.Instance.ProcessKeyword(shares, ProcessKeywordMode.FillOriginalText);

                    for (int i = 0; i < denouncings.Count; i++)
                    {
                        for (int j = 0; j < shares.Count; j++)
                        {
                            if (denouncings[i].TargetID == shares[j].ShareID)
                            {
                                denouncings[i].TargetShare = shares[j];
                                break;
                            }
                        }
                    }
                }
                return(denouncings);
            }
        }
Beispiel #46
0
		public override ShareCollection GetSharesBySearch(Guid[] excludeRoleIDs, ShareFilter filter, int pageNumber)
		{
			using (SqlQuery query = new SqlQuery())
			{
				string sqlCondition = BuildConditionsByFilter(query, filter, excludeRoleIDs, false);

                query.Pager.TableName = "[bx_SharesView]";
				query.Pager.SortField = filter.Order.ToString();

				if (filter.Order != ShareFilter.OrderBy.ShareID)
				{
					query.Pager.PrimaryKey = "ShareID";
				}

				query.Pager.PageNumber = pageNumber;
				query.Pager.PageSize = filter.PageSize;
				query.Pager.SelectCount = true;
				query.Pager.IsDesc = filter.IsDesc;

				query.Pager.Condition = sqlCondition;


				using (XSqlDataReader reader = query.ExecuteReader())
				{
					ShareCollection shares = new ShareCollection(reader);

					if (reader.NextResult())
					{
						if (reader.Read())
						{
							shares.TotalRecords = reader.Get<int>(0);
						}
					}

					return shares;
				}
			}
		}