Joining









How do I use Joining
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: NetworkingPeer.cs Copy
800     private void SendPlayerName()
801     {
802         if (this.State == global::PeerState.Joining)
803         {
804             // this means, the join on the gameServer is sent (with an outdated name). send the new when in game
805             this.mPlayernameHasToBeUpdated = true;
806             return;
807         }
808
809         if (this.mLocalActor != null)
810         {
811             this.mLocalActor.name = this.PlayerName;
812             Hashtable properties = new Hashtable();
813             properties[ActorProperties.PlayerName] = this.PlayerName;
814             if (this.mLocalActor.ID > 0)
815             {
816                 this.OpSetPropertiesOfActor(this.mLocalActor.ID, properties, true, (byte)0);
817                 this.mPlayernameHasToBeUpdated = false;
818             }
819         }
820     }
File name: NetworkingPeer.cs Copy
1016     public void OnOperationResponse(OperationResponse operationResponse)
1017     {
1018         if (PhotonNetwork.networkingPeer.State == global::PeerState.Disconnecting)
1019         {
1020             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1021             {
1022                 Debug.Log("OperationResponse ignored while disconnecting. Code: " + operationResponse.OperationCode);
1023             }
1024             return;
1025         }
1026
1027         // extra logging for error debugging (helping developers with a bit of automated analysis)
1028         if (operationResponse.ReturnCode == 0)
1029         {
1030             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1031                 Debug.Log(operationResponse.ToString());
1032         }
1033         else
1034         {
1035             if (operationResponse.ReturnCode == ErrorCode.OperationNotAllowedInCurrentState)
1036             {
1037                 Debug.LogError("Operation " + operationResponse.OperationCode + " could not be executed (yet). Wait for state JoinedLobby or ConnectedToMaster and their callbacks before calling operations. WebRPCs need a server-side configuration. Enum OperationCode helps identify the operation.");
1038             }
1039             else if (operationResponse.ReturnCode == ErrorCode.WebHookCallFailed)
1040             {
1041                 Debug.LogError("Operation " + operationResponse.OperationCode + " failed in a server-side plugin. Check the configuration in the Dashboard. Message from server-plugin: " + operationResponse.DebugMessage);
1042             }
1043             else if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1044             {
1045                 Debug.LogError("Operation failed: " + operationResponse.ToStringFull() + " Server: " + this.server);
1046             }
1047         }
1048
1049         // use the "secret" or "token" whenever we get it. doesn't really matter if it's in AuthResponse.
1050         if (operationResponse.Parameters.ContainsKey(ParameterCode.Secret))
1051         {
1052             if (this.CustomAuthenticationValues == null)
1053             {
1054                 this.CustomAuthenticationValues = new AuthenticationValues();
1055                 // this.DebugReturn(DebugLevel.ERROR, "Server returned secret. Created CustomAuthenticationValues.");
1056             }
1057
1058             this.CustomAuthenticationValues.Secret = operationResponse[ParameterCode.Secret] as string;
1059         }
1060
1061         switch (operationResponse.OperationCode)
1062         {
1063             case OperationCode.Authenticate:
1064                 {
1065                     // PeerState oldState = this.State;
1066
1067                     if (operationResponse.ReturnCode != 0)
1068                     {
1069                         if (operationResponse.ReturnCode == ErrorCode.InvalidOperationCode)
1070                         {
1071                             Debug.LogError(string.Format("If you host Photon yourself, make sure to start the 'Instance LoadBalancing' "+ this.ServerAddress));
1072                         }
1073                         else if (operationResponse.ReturnCode == ErrorCode.InvalidAuthentication)
1074                         {
1075                             Debug.LogError(string.Format("The appId this client sent is unknown on the server (Cloud). Check settings. If using the Cloud, check account."));
1076                             SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, DisconnectCause.InvalidAuthentication);
1077                         }
1078                         else if (operationResponse.ReturnCode == ErrorCode.CustomAuthenticationFailed)
1079                         {
1080                             Debug.LogError(string.Format("Custom Authentication failed (either due to user-input or configuration or AuthParameter string format). Calling: OnCustomAuthenticationFailed()"));
1081                             SendMonoMessage(PhotonNetworkingMessage.OnCustomAuthenticationFailed, operationResponse.DebugMessage);
1082                         }
1083                         else
1084                         {
1085                             Debug.LogError(string.Format("Authentication failed: '{0}' Code: {1}", operationResponse.DebugMessage, operationResponse.ReturnCode));
1086                         }
1087
1088                         this.State = global::PeerState.Disconnecting;
1089                         this.Disconnect();
1090
1091                         if (operationResponse.ReturnCode == ErrorCode.MaxCcuReached)
1092                         {
1093                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1094                                 Debug.LogWarning(string.Format("Currently, the limit of users is reached for this title. Try again later. Disconnecting"));
1095                             SendMonoMessage(PhotonNetworkingMessage.OnPhotonMaxCccuReached);
1096                             SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, DisconnectCause.MaxCcuReached);
1097                         }
1098                         else if (operationResponse.ReturnCode == ErrorCode.InvalidRegion)
1099                         {
1100                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1101                                 Debug.LogError(string.Format("The used master server address is not available with the subscription currently used. Got to Photon Cloud Dashboard or change URL. Disconnecting."));
1102                             SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, DisconnectCause.InvalidRegion);
1103                         }
1104                         else if (operationResponse.ReturnCode == ErrorCode.AuthenticationTicketExpired)
1105                         {
1106                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1107                                 Debug.LogError(string.Format("The authentication ticket expired. You need to connect (and authenticate) again. Disconnecting."));
1108                             SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, DisconnectCause.AuthenticationTicketExpired);
1109                         }
1110                         break;
1111                     }
1112                     else
1113                     {
1114                         if (this.server == ServerConnection.NameServer)
1115                         {
1116                             // on the NameServer, authenticate returns the MasterServer address for a region and we hop off to there
1117                             this.MasterServerAddress = operationResponse[ParameterCode.Address] as string;
1118                             this.DisconnectToReconnect();
1119                         }
1120                         else if (this.server == ServerConnection.MasterServer)
1121                         {
1122                             if (PhotonNetwork.autoJoinLobby)
1123                             {
1124                                 this.State = global::PeerState.Authenticated;
1125                                 this.OpJoinLobby(this.lobby);
1126                             }
1127                             else
1128                             {
1129                                 this.State = global::PeerState.ConnectedToMaster;
1130                                 NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnConnectedToMaster);
1131                             }
1132                         }
1133                         else if (this.server == ServerConnection.GameServer)
1134                         {
1135                             this.State = global::PeerState.Joining;
1136
1137                             if (this.mLastJoinType == JoinType.JoinGame || this.mLastJoinType == JoinType.JoinRandomGame || this.mLastJoinType == JoinType.JoinOrCreateOnDemand)
1138                             {
1139                                 // if we just "join" the game, do so. if we wanted to "create the room on demand", we have to send this to the game server as well.
1140                                 this.OpJoinRoom(this.mRoomToGetInto.name, this.mRoomOptionsForCreate, this.mRoomToEnterLobby, this.mLastJoinType == JoinType.JoinOrCreateOnDemand);
1141                             }
1142                             else if (this.mLastJoinType == JoinType.CreateGame)
1143                             {
1144                                 // on the game server, we have to apply the room properties that were chosen for creation of the room, so we use this.mRoomToGetInto
1145                                 this.OpCreateGame(this.mRoomToGetInto.name, this.mRoomOptionsForCreate, this.mRoomToEnterLobby);
1146                             }
1147
1148                             break;
1149                         }
1150                     }
1151                     break;
1152                 }
1153
1154             case OperationCode.GetRegions:
1155                 // Debug.Log("GetRegions returned: " + operationResponse.ToStringFull());
1156
1157                 if (operationResponse.ReturnCode == ErrorCode.InvalidAuthentication)
1158                 {
1159                     Debug.LogError(string.Format("The appId this client sent is unknown on the server (Cloud). Check settings. If using the Cloud, check account."));
1160                     SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, DisconnectCause.InvalidAuthentication);
1161
1162                     this.State = global::PeerState.Disconnecting;
1163                     this.Disconnect();
1164                     return;
1165                 }
1166
1167                 string[] regions = operationResponse[ParameterCode.Region] as string[];
1168                 string[] servers = operationResponse[ParameterCode.Address] as string[];
1169
1170                 if (regions == null || servers == null || regions.Length != servers.Length)
1171                 {
1172                     Debug.LogError("The region arrays from Name Server are not ok. Must be non-null and same length.");
1173                     break;
1174                 }
1175
1176                 this.AvailableRegions = new List(regions.Length);
1177                 for (int i = 0; i < regions.Length; i++)
1178                 {
1179                     string regionCodeString = regions[i];
1180                     if (string.IsNullOrEmpty(regionCodeString))
1181                     {
1182                         continue;
1183                     }
1184                     regionCodeString = regionCodeString.ToLower();
1185
1186                     CloudRegionCode code = Region.Parse(regionCodeString);
1187                     this.AvailableRegions.Add(new Region() { Code = code, HostAndPort = servers[i] });
1188                 }
1189
1190                 // PUN assumes you fetch the name-server's list of regions to ping them
1191                 if (PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.BestRegion)
1192                 {
1193                     PhotonHandler.PingAvailableRegionsAndConnectToBest();
1194                 }
1195                 break;
1196
1197             case OperationCode.CreateGame:
1198                 {
1199                     if (this.server == ServerConnection.GameServer)
1200                     {
1201                         this.GameEnteredOnGameServer(operationResponse);
1202                     }
1203                     else
1204                     {
1205                         if (operationResponse.ReturnCode != 0)
1206                         {
1207                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1208                                 Debug.LogWarning(string.Format("CreateRoom failed, client stays on masterserver: {0}.", operationResponse.ToStringFull()));
1209
1210                             SendMonoMessage(PhotonNetworkingMessage.OnPhotonCreateRoomFailed);
1211                             break;
1212                         }
1213
1214                         string gameID = (string) operationResponse[ParameterCode.RoomName];
1215                         if (!string.IsNullOrEmpty(gameID))
1216                         {
1217                             // is only sent by the server's response, if it has not been
1218                             // sent with the client's request before!
1219                             this.mRoomToGetInto.name = gameID;
1220                         }
1221
1222                         this.mGameserver = (string)operationResponse[ParameterCode.Address];
1223                         this.DisconnectToReconnect();
1224                     }
1225
1226                     break;
1227                 }
1228
1229             case OperationCode.JoinGame:
1230                 {
1231                     if (this.server != ServerConnection.GameServer)
1232                     {
1233                         if (operationResponse.ReturnCode != 0)
1234                         {
1235                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1236                                 Debug.Log(string.Format("JoinRoom failed (room maybe closed by now). Client stays on masterserver: {0}. State: {1}", operationResponse.ToStringFull(), this.State));
1237
1238                             SendMonoMessage(PhotonNetworkingMessage.OnPhotonJoinRoomFailed);
1239                             break;
1240                         }
1241
1242                         this.mGameserver = (string)operationResponse[ParameterCode.Address];
1243                         this.DisconnectToReconnect();
1244                     }
1245                     else
1246                     {
1247                         this.GameEnteredOnGameServer(operationResponse);
1248                     }
1249
1250                     break;
1251                 }
1252
1253             case OperationCode.JoinRandomGame:
1254                 {
1255                     // happens only on master. on gameserver, this is a regular join (we don't need to find a random game again)
1256                     // the operation OpJoinRandom either fails (with returncode 8) or returns game-to-join information
1257                     if (operationResponse.ReturnCode != 0)
1258                     {
1259                         if (operationResponse.ReturnCode == ErrorCode.NoRandomMatchFound)
1260                         {
1261                             if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1262                                 Debug.Log("JoinRandom failed: No open game. Calling: OnPhotonRandomJoinFailed() and staying on master server.");
1263                         }
1264                         else if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1265                         {
1266                             Debug.LogWarning(string.Format("JoinRandom failed: {0}.", operationResponse.ToStringFull()));
1267                         }
1268
1269                         SendMonoMessage(PhotonNetworkingMessage.OnPhotonRandomJoinFailed, operationResponse.ReturnCode, operationResponse.DebugMessage);
1270                         break;
1271                     }
1272
1273                     string roomName = (string)operationResponse[ParameterCode.RoomName];
1274                     this.mRoomToGetInto.name = roomName;
1275                     this.mGameserver = (string)operationResponse[ParameterCode.Address];
1276                     this.DisconnectToReconnect();
1277                     break;
1278                 }
1279
1280             case OperationCode.JoinLobby:
1281                 this.State = global::PeerState.JoinedLobby;
1282                 this.insideLobby = true;
1283                 SendMonoMessage(PhotonNetworkingMessage.OnJoinedLobby);
1284
1285                 // this.mListener.joinLobbyReturn();
1286                 break;
1287             case OperationCode.LeaveLobby:
1288                 this.State = global::PeerState.Authenticated;
1289                 this.LeftLobbyCleanup(); // will set insideLobby = false
1290                 break;
1291
1292             case OperationCode.Leave:
1293                 this.DisconnectToReconnect();
1294                 break;
1295
1296             case OperationCode.SetProperties:
1297                 // this.mListener.setPropertiesReturn(returnCode, debugMsg);
1298                 break;
1299
1300             case OperationCode.GetProperties:
1301                 {
1302                     Hashtable actorProperties = (Hashtable)operationResponse[ParameterCode.PlayerProperties];
1303                     Hashtable gameProperties = (Hashtable)operationResponse[ParameterCode.GameProperties];
1304                     this.ReadoutProperties(gameProperties, actorProperties, 0);
1305
1306                     // RemoveByteTypedPropertyKeys(actorProperties, false);
1307                     // RemoveByteTypedPropertyKeys(gameProperties, false);
1308                     // this.mListener.getPropertiesReturn(gameProperties, actorProperties, returnCode, debugMsg);
1309                     break;
1310                 }
1311
1312             case OperationCode.RaiseEvent:
1313                 // this usually doesn't give us a result. only if the caching is affected the server will send one.
1314                 break;
1315
1316             case OperationCode.FindFriends:
1317                 bool[] onlineList = operationResponse[ParameterCode.FindFriendsResponseOnlineList] as bool[];
1318                 string[] roomList = operationResponse[ParameterCode.FindFriendsResponseRoomIdList] as string[];
1319
1320                 if (onlineList != null && roomList != null && this.friendListRequested != null && onlineList.Length == this.friendListRequested.Length)
1321                 {
1322                     List friendList = new List(this.friendListRequested.Length);
1323                     for (int index = 0; index < this.friendListRequested.Length; index++)
1324                     {
1325                         FriendInfo friend = new FriendInfo();
1326                         friend.Name = this.friendListRequested[index];
1327                         friend.Room = roomList[index];
1328                         friend.IsOnline = onlineList[index];
1329                         friendList.Insert(index, friend);
1330                     }
1331                     PhotonNetwork.Friends = friendList;
1332                 }
1333                 else
1334                 {
1335                     // any of the lists is null and shouldn't. print a error
1336                     Debug.LogError("FindFriends failed to apply the result, as a required value wasn't provided or the friend list length differed from result.");
1337                 }
1338
1339                 this.friendListRequested = null;
1340                 this.isFetchingFriends = false;
1341                 this.friendListTimestamp = Environment.TickCount;
1342                 if (this.friendListTimestamp == 0)
1343                 {
1344                     this.friendListTimestamp = 1; // makes sure the timestamp is not accidentally 0
1345                 }
1346
1347                 SendMonoMessage(PhotonNetworkingMessage.OnUpdatedFriendList);
1348                 break;
1349
1350             case OperationCode.WebRpc:
1351                 SendMonoMessage(PhotonNetworkingMessage.OnWebRpcResponse, operationResponse);
1352                 break;
1353
1354             default:
1355                 Debug.LogWarning(string.Format("OperationResponse unhandled: {0}", operationResponse.ToString()));
1356                 break;
1357         }
1358
1359         this.externalListener.OnOperationResponse(operationResponse);
1360     }
File name: NetworkingPeer.cs Copy
3339     private void OnSerializeRead(Hashtable data, PhotonPlayer sender, int networkTime, short correctPrefix)
3340     {
3341         // read view ID from key (byte)0: a int-array (PUN 1.17++)
3342         int viewID = (int)data[(byte)0];
3343
3344
3345         PhotonView view = this.GetPhotonView(viewID);
3346         if (view == null)
3347         {
3348             Debug.LogWarning("Received OnSerialization for view ID " + viewID + ". We have no such PhotonView! Ignored this if you're leaving a room. State: " + this.State);
3349             return;
3350         }
3351
3352         if (view.prefix > 0 && correctPrefix != view.prefix)
3353         {
3354             Debug.LogError("Received OnSerialization for view ID " + viewID + " with prefix " + correctPrefix + ". Our prefix is " + view.prefix);
3355             return;
3356         }
3357
3358         // SetReceiving filtering
3359         if (view.group != 0 && !this.allowedReceivingGroups.Contains(view.group))
3360         {
3361             return; // Ignore group
3362         }
3363
3364
3365         if (view.synchronization == ViewSynchronization.ReliableDeltaCompressed)
3366         {
3367             if (!this.DeltaCompressionRead(view, data))
3368             {
3369                 // Skip this packet as we haven't got received complete-copy of this view yet.
3370                 if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
3371                     Debug.Log("Skipping packet for " + view.name + " [" + view.viewID + "] as we haven't received a full packet for delta compression yet. This is OK if it happens for the first few frames after joining a game.");
3372                 return;
3373             }
3374
3375             // store last received for delta-compression usage
3376             view.lastOnSerializeDataReceived = data[(byte)1] as object[];
3377         }
3378
3379         if (sender.ID != view.ownerId)
3380         {
3381             if (!view.isSceneView || !sender.isMasterClient)
3382             {
3383                 // obviously the owner changed and we didn't yet notice.
3384                 Debug.Log("Adjusting owner to sender of updates. From: " + view.ownerId + " to: " + sender.ID);
3385                 view.ownerId = sender.ID;
3386             }
3387         }
3388
3389         object[] contents = data[(byte)1] as object[];
3390         PhotonStream pStream = new PhotonStream(false, contents);
3391         PhotonMessageInfo info = new PhotonMessageInfo(sender, networkTime, view);
3392
3393         view.DeserializeView( pStream, info );
3394     }
File name: PhotonNetwork.cs Copy
113     {
114         get
115         {
116             // connected property will check offlineMode and networkingPeer being null
117             if (!connected)
118             {
119                 return false;
120             }
121
122             if (offlineMode)
123             {
124                 return true;
125             }
126
127             switch (connectionStateDetailed)
128             {
129                 case PeerState.PeerCreated:
130                 case PeerState.Disconnected:
131                 case PeerState.Disconnecting:
132                 case PeerState.Authenticating:
133                 case PeerState.ConnectingToGameserver:
134                 case PeerState.ConnectingToMasterserver:
135                 case PeerState.ConnectingToNameServer:
136                 case PeerState.Joining:
137                 case PeerState.Leaving:
138                     return false; // we are not ready to execute any operations
139             }
140
141             return true;
142         }
143     }
File name: PhotonNetwork.cs Copy
1510     public static bool JoinRoom(string roomName, bool createIfNotExists)
1511     {
1512         if (connectionStateDetailed == PeerState.Joining || connectionStateDetailed == PeerState.Joined || connectionStateDetailed == PeerState.ConnectedToGameserver)
1513         {
1514             Debug.LogError("JoinRoom aborted: You can only join a room while not currently connected/connecting to a room.");
1515         }
1516         else if (room != null)
1517         {
1518             Debug.LogError("JoinRoom aborted: You are already in a room!");
1519         }
1520         else if (roomName == string.Empty)
1521         {
1522             Debug.LogError("JoinRoom aborted: You must specifiy a room name!");
1523         }
1524         else
1525         {
1526             if (offlineMode)
1527             {
1528                 offlineModeRoom = new Room(roomName, null);
1529                 NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom);
1530                 return true;
1531             }
1532             else
1533             {
1534                 return networkingPeer.OpJoinRoom(roomName, null, null, createIfNotExists);
1535             }
1536         }
1537
1538         return false; // offline and OpJoin both return but the error-cases don't
1539     }
File name: frmCustomerRegistration.cs Copy
30         private void Register_Click(object sender, EventArgs e)
31         {
32             if (txtUsername.Text == "")
33             {
34                 MessageBox.Show("Please enter username", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
35                 txtUsername.Focus();
36                 return;
37             }
38
39             if (txtPassword.Text == "")
40             {
41                 MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
42                 txtPassword.Focus();
43                 return;
44             }
45             if (txtName.Text == "")
46             {
47                 MessageBox.Show("Please enter name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
48                 txtName.Focus();
49                 return;
50             }
51             if (txtContact_no.Text == "")
52             {
53                 MessageBox.Show("Please enter contact no.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
54                 txtContact_no.Focus();
55                 return;
56             }
57             if (txtEmail_Address.Text == "")
58             {
59                 MessageBox.Show("Please enter email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
60                 txtEmail_Address.Focus();
61                 return;
62             }
63             try
64             {
65                 con = new SqlConnection(cs.DBConn);
66                 con.Open();
67                 string ct = "select username from registration where username=@find";
68
69                 cmd = new SqlCommand(ct);
70                 cmd.Connection = con;
71                 cmd.Parameters.Add(new SqlParameter("@find", System.Data.SqlDbType.NChar, 30, "username"));
72                 cmd.Parameters["@find"].Value = txtUsername.Text;
73                 rdr = cmd.ExecuteReader();
74
75                 if (rdr.Read())
76                 {
77                     MessageBox.Show("Username Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
78                     txtUsername.Text = "";
79                     txtUsername.Focus();
80
81
82                     if ((rdr != null))
83                     {
84                         rdr.Close();
85                     }
86                     return;
87                 }
88                 con = new SqlConnection(cs.DBConn);
89                 con.Open();
90                 string ct1 = "select Email from registration where Email='" + txtEmail_Address.Text + "'";
91
92                 cmd = new SqlCommand(ct1);
93                 cmd.Connection = con;
94                 rdr = cmd.ExecuteReader();
95
96                 if (rdr.Read())
97                 {
98                     MessageBox.Show("Email ID Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
99                     txtEmail_Address.Text = "";
100                     txtEmail_Address.Focus();
101
102
103                     if ((rdr != null))
104                     {
105                         rdr.Close();
106                     }
107                     return;
108                 }
109                 con = new SqlConnection(cs.DBConn);
110                 con.Open();
111
112                 string cb = "insert into Registration(Username,UserType,Password,ContactNo,Email,Name,JoiningDate) VALUES ('" + txtUsername.Text + "','Customer','" + txtPassword.Text + "','" + txtContact_no.Text + "','" + txtEmail_Address.Text + "','" + txtName.Text + "','" + System.DateTime.Now + "')";
113
114                 cmd = new SqlCommand(cb);
115                 cmd.Connection = con;
116                 cmd.ExecuteReader();
117                 con.Close();
118                 MessageBox.Show("Successfully Registered", "User", MessageBoxButtons.OK, MessageBoxIcon.Information);
119
120             }
121             catch (Exception ex)
122             {
123                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
124             }
125         }
File name: frmRegisteredUsersDetails.cs Copy
29         public DataView GetData()
30         {
31             dynamic SelectQry = "SELECT RTRIM(Username) as [User Name],RTRIM(Password) as [Password],RTRIM(Name) as [Name],RTRIM(ContactNo) as [Contact No.],RTRIM(Email) as [Email ID],RTRIM(joiningdate) as [Date Of Joining] FROM registration";
32             DataSet SampleSource = new DataSet();
33             DataView TableView = null;
34             try
35             {
36                 SqlCommand SampleCommand = new SqlCommand();
37                 dynamic SampleDataAdapter = new SqlDataAdapter();
38                 SampleCommand.CommandText = SelectQry;
39                 SampleCommand.Connection = Connection;
40                 SampleDataAdapter.SelectCommand = SampleCommand;
41                 SampleDataAdapter.Fill(SampleSource);
42                 TableView = SampleSource.Tables[0].DefaultView;
43             }
44             catch (Exception ex)
45             {
46                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
47             }
48             return TableView;
49         }
File name: frmRegistration.cs Copy
48         private void Register_Click(object sender, EventArgs e)
49         {
50             if (txtUsername.Text == "")
51             {
52                 MessageBox.Show("Please enter username", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
53                 txtUsername.Focus();
54                 return;
55             }
56             if (cmbUserType.Text == "")
57             {
58                 MessageBox.Show("Please select user type", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
59                 cmbUserType.Focus();
60                 return;
61             }
62             if (txtPassword.Text == "")
63             {
64                 MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
65                 txtPassword.Focus();
66                 return;
67             }
68             if (txtName.Text == "")
69             {
70                 MessageBox.Show("Please enter name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
71                 txtName.Focus();
72                 return;
73             }
74             if (txtContact_no.Text == "")
75             {
76                 MessageBox.Show("Please enter contact no.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
77                 txtContact_no.Focus();
78                 return;
79             }
80             if (txtEmail_Address.Text == "")
81             {
82                 MessageBox.Show("Please enter email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
83                 txtEmail_Address.Focus();
84                 return;
85             }
86             try
87             {
88                 con = new SqlConnection(cs.DBConn);
89                 con.Open();
90                 string ct = "select username from registration where username=@find";
91
92                 cmd = new SqlCommand(ct);
93                 cmd.Connection = con;
94                 cmd.Parameters.Add(new SqlParameter("@find", System.Data.SqlDbType.NChar, 30, "username"));
95                 cmd.Parameters["@find"].Value = txtUsername.Text;
96                 rdr = cmd.ExecuteReader();
97
98                 if (rdr.Read())
99                 {
100                     MessageBox.Show("Username Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
101                     txtUsername.Text = "";
102                     txtUsername.Focus();
103
104
105                     if ((rdr != null))
106                     {
107                         rdr.Close();
108                     }
109                     return;
110                 }
111                 con = new SqlConnection(cs.DBConn);
112                 con.Open();
113                 string ct1 = "select Email from registration where Email='" + txtEmail_Address.Text + "'";
114
115                 cmd = new SqlCommand(ct1);
116                 cmd.Connection = con;
117                 rdr = cmd.ExecuteReader();
118
119                 if (rdr.Read())
120                 {
121                     MessageBox.Show("Email ID Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
122                     txtEmail_Address.Text = "";
123                     txtEmail_Address.Focus();
124
125
126                     if ((rdr != null))
127                     {
128                         rdr.Close();
129                     }
130                     return;
131                 }
132                 con = new SqlConnection(cs.DBConn);
133                 con.Open();
134
135                 string cb = "insert into Registration(Username,UsertYpe,Password,ContactNo,Email,Name,JoiningDate) VALUES ('" + txtUsername.Text + "','" + cmbUserType.Text + "','" + txtPassword.Text + "','" + txtContact_no.Text + "','" + txtEmail_Address.Text + "','" + txtName.Text + "','" + System.DateTime.Now + "')";
136
137                 cmd = new SqlCommand(cb);
138                 cmd.Connection = con;
139                 cmd.ExecuteReader();
140                 con.Close();
141                 MessageBox.Show("Successfully Registered", "User", MessageBoxButtons.OK, MessageBoxIcon.Information);
142                 Autocomplete();
143                 btnRegister.Enabled = false;
144
145             }
146             catch (Exception ex)
147             {
148                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
149             }
150         }

Joining 146 lượt xem

Gõ tìm kiếm nhanh...