using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Fluent; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Data; using Extensiones; using static Extensiones.ModExtensiones; public partial class GPS_Shipments : ClsPaginas { #region "P R O P I E D A D E S" public int CveShipment { get { return IfNull(ViewState["CveShipment"], -1).ToString().ToEntero(); } set { ViewState["CveShipment"] = value; } } public string UsuarioFV { get { return IfNull(ViewState["UsuarioFV"], "").ToString(); } set { ViewState["UsuarioFV"] = value; } } public string ContraseniaFV { get { return IfNull(ViewState["ContraseniaFV"], "").ToString(); } set { ViewState["ContraseniaFV"] = value; } } public string FVTHIRDPARTYID { get { return IfNull(ViewState["fvThirdPartyId"], "").ToString(); } set { ViewState["fvThirdPartyId"] = value; } } public string SCAC { get { return IfNull(ViewState["SCAC"], "").ToString(); } set { ViewState["SCAC"] = value; } } public string FVCARRIERID { get { return IfNull(ViewState["FVCARRIERID"], "").ToString(); } set { ViewState["FVCARRIERID"] = value; } } private DataTable DtStops { get { return (DataTable)ViewState["DtStops"]; } set { ViewState["DtStops"] = value; } } private string Token => Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Decripta(UsuarioFV), Decripta(ContraseniaFV)))); #endregion #region "D A T O S" private void IniciaDTStops() { if (this.DtStops != null) { this.DtStops.Dispose(); this.DtStops = null; } this.DtStops = new DataTable(); this.DtStops.Columns.Add(new DataColumn("StopSequence", typeof(int))); this.DtStops.Columns.Add(new DataColumn("Name", typeof(string))); this.DtStops.Columns.Add(new DataColumn("LocationID", typeof(string))); this.DtStops.Columns.Add(new DataColumn("StopType", typeof(string))); this.DtStops.Columns.Add(new DataColumn("StopRole", typeof(string))); this.DtStops.Columns.Add(new DataColumn("EarlyArrivalTime", typeof(DateTime))); this.DtStops.Columns.Add(new DataColumn("LateArrivalTime", typeof(DateTime))); this.DtStops.Columns.Add(new DataColumn("Address", typeof(string))); this.DtStops.Columns.Add(new DataColumn("City", typeof(string))); this.DtStops.Columns.Add(new DataColumn("State", typeof(string))); this.DtStops.Columns.Add(new DataColumn("PostalCode", typeof(string))); this.DtStops.Columns.Add(new DataColumn("Country", typeof(string))); this.DtStops.Columns.Add(new DataColumn("Lat", typeof(string))); this.DtStops.Columns.Add(new DataColumn("Lon", typeof(string))); } #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { CargaConfiguracion(); CargaDatos(); } } protected void CargaConfiguracion() { var ObjGPS = new ClsGPS(); try { if (ObjGPS.GetFVConfiguracion(UsuarioActual.CveCliente, -1)) { if (ObjGPS.DtResultados.Rows.Count == 1) { var row = ObjGPS.DtResultados.Rows[0]; this.FVCARRIERID = row["fvCarrierId"].ToString().Trim(); this.FVTHIRDPARTYID = row["fvThirdPartyId"].ToString().Trim(); this.SCAC = row["scac"].ToString().Trim(); this.UsuarioFV = Encripta(row["Usuario"].ToString()).Trim(); this.ContraseniaFV = Encripta(row["Contrasenia"].ToString()).Trim(); } else { Alert("No esta configurado para utilizar este modulo", TipoMensaje.MsgAdvertencia); } } DdlDispositivo.DataSource = get_GlobalDTDispositivosUsuarios(UsuarioActual.CveCliente, UsuarioActual.CveUsuario).FiltraParametros("Estatus = 1"); DdlDispositivo.DataBind(); } catch (Exception ex) { this.OnError("Ocurrió un error al obtener la configuración", ex); } finally { ObjGPS.Dispose(); } } protected void CargaDatos() { var ObjGPS = new ClsGPS(); if (ObjGPS.GetShipments(UsuarioActual.CveCliente, -1)) { GvShipments.DataSource = ObjGPS.DtResultados; } ObjGPS.Dispose(); GvShipments.DataBind(); IniciaDTStops(); LimpiarModal(); LimpiarModalStop(); } protected void LnkAgregar_Click(object sender, EventArgs e) { IniciaDTStops(); LimpiarModal(); this.RegistraScript("$('#DivShipment').modal({backdrop: 'static', keyboard: false});"); } protected void LnkAddNewStop_Click(object sender, EventArgs e) { LimpiarModalStop(); this.RegistraScript("$('#DivStop').modal({backdrop: 'static', keyboard: false});"); } protected void LnkAddStop_Click(object sender, EventArgs e) { if (DtStops != null) { var Row = DtStops.NewRow(); Row["StopSequence"] = DtStops.Rows.Count + 1; Row["Name"] = TxtLocName.Text.Trim(); Row["LocationID"] = TxtLocID.Text.Trim(); Row["StopType"] = DdlStopType.SelectedValue; Row["StopRole"] = DdlStopRole.SelectedValue; Row["EarlyArrivalTime"] = TxtFechaStopI.Text.ToDateTime(); Row["LateArrivalTime"] = TxtFechaStopF.Text.ToDateTime(); Row["Address"] = TxtAddress.Text.Trim(); Row["City"] = TxtCity.Text.Trim(); Row["State"] = TxtState.Text.Trim(); Row["PostalCode"] = TxtPostalCode.Text.Trim(); Row["Country"] = TxtContry.Text.Trim(); var latlon = TxtLatLong.Text.Trim().Split(','); Row["Lat"] = latlon[0]; Row["Lon"] = latlon[1]; DtStops.Rows.Add(Row); } GvStops.DataSource = DtStops; GvStops.DataBind(); UpShipment.Update(); this.RegistraScript("$('#DivStop').modal('hide');"); } protected void LimpiarModal() { TxtShipment.Text = ""; TxtAsset.Text = ""; TxtRoute.Text = ""; TxtTrailer.Text = ""; TxtObs.Text = ""; UpShipment.Update(); } protected void LimpiarModalStop() { TxtLocName.Text = ""; TxtLocID.Text = ""; TxtLoc.Text = ""; TxtFechaStopI.Text = ""; TxtFechaStopF.Text = ""; TxtAddress.Text = ""; TxtCity.Text = ""; TxtState.Text = ""; TxtPostalCode.Text = ""; TxtContry.Text = ""; TxtLatLong.Text = ""; UpStop.Update(); } #region "C R E A R E Q U E S T" protected JObject GeneraRequestShipment() { var stops = GeneraStops(); return new JObject() { new JProperty("carrier", new JObject() { new JProperty("fvCarrierId", FVCARRIERID), new JProperty("scac", SCAC) }), new JProperty("customer",new JObject() { new JProperty("fvCustomerId", DdlCustomer.SelectedValue.Trim()) }), new JProperty("thirdParty",new JObject() { new JProperty("fvThirdPartyId", FVTHIRDPARTYID) }), new JProperty("shipmentIdentification",new JObject() { new JProperty("shipmentId", TxtShipment.Text.Trim()) }), new JProperty("telematics",new JObject() { new JProperty("provider", "Direct"), new JProperty("trackingAssetId", TxtAsset.Text.Trim()) }), new JProperty("shipmentDetails",new JObject()), new JProperty("stops",stops), new JProperty("shipmentReferences",new JArray() { new JObject() { new JProperty("qualifier", "route_id"), new JProperty("description", ""), new JProperty("value",TxtRoute.Text.Trim()) }, new JObject() { new JProperty("qualifier", "trailer_number"), new JProperty("description", ""), new JProperty("value",TxtTrailer.Text.Trim()) } }) }; } protected JArray GeneraStops() { return new JArray(from row in DtStops.AsEnumerable() select new JObject( new JProperty("stopType", row["StopType"]), new JProperty("stopRole", row["StopRole"]), new JProperty("stopSequence", row["StopSequence"].ToString().ToEntero()), new JProperty("earlyArrival", string.Format("{0}{1}", row["EarlyArrivalTime"].ToString().ToDateTime().ToString("yyyy-MM-ddThh:mm:ss"), "-0500")), new JProperty("lateArrival", string.Format("{0}{1}", row["LateArrivalTime"].ToString().ToDateTime().ToString("yyyy-MM-ddThh:mm:ss"), "-0500")), new JProperty("location", new JObject() { new JProperty("locationId", new JObject() { new JProperty("qualifier", "customer"), new JProperty("value", row["LocationID"]) }), new JProperty("name", row["Name"]), new JProperty("address1",row["Address"]), new JProperty("city",row["City"]), new JProperty("state",row["State"]), new JProperty("postalCode",row["PostalCode"]), new JProperty("country",row["Country"]), new JProperty("latitude",row["Lat"].ToString().ToDouble()), new JProperty("longitude",row["Lon"].ToString().ToDouble()) }) )); } protected JObject GeneraRequestEvent(int CveShipment) { var route_id = ""; var trailer_number = ""; var trackingAssetId = ""; var ObjGPS = new ClsGPS(); if (ObjGPS.GetShipments(UsuarioActual.CveCliente, CveShipment)) { if (ObjGPS.DtResultados.Rows.Count == 1) { var row = ObjGPS.DtResultados.Rows[0]; route_id = row["RouteID"].ToString(); trailer_number = row["TrailerID"].ToString(); trackingAssetId = row["AssetID"].ToString(); } } ObjGPS.Dispose(); var latlon = TxtLatLongEvent.Text.Trim().Split(','); var json = new JObject() { new JProperty("carrier", new JObject() { new JProperty("fvCarrierId", FVCARRIERID), new JProperty("scac", SCAC) }), new JProperty("location",new JObject() { new JProperty("latitude", latlon[0].ToDouble()), new JProperty("longitude", latlon[1].ToDouble()) }), new JProperty("telematics",new JObject() { new JProperty("provider", "Direct"), new JProperty("trackingAssetId", trackingAssetId) }), new JProperty("eventDetail",new JObject() { new JProperty("event", DdlEvent.SelectedValue), new JProperty("reason",DdlReason.SelectedValue), new JProperty("eventDate",string.Format("{0}{1}",UsuarioActual.FechaActualCliente.ToString("yyyy-MM-ddThh:mm:ss"),"-0500")) }), new JProperty("eventReferences",new JArray() { new JObject() { new JProperty("qualifier", "route_id"), new JProperty("description", ""), new JProperty("value",route_id) }, new JObject() { new JProperty("qualifier", "trailer_number"), new JProperty("description", ""), new JProperty("value",trailer_number) } }) }; if (DdlEvent.SelectedValue != "LO") { json.Add(new JProperty("stopSequence", 1)); } return json; } protected JObject GeneraRequestLO(int CveShipment) { var route_id = ""; var trailer_number = ""; var trackingAssetId = ""; double lat = 0; double lon = 0; var ObjGPS = new ClsGPS(); if (ObjGPS.GetShipmentDetail(CveShipment)) { if (ObjGPS.DtResultados.Rows.Count == 1) { var row = ObjGPS.DtResultados.Rows[0]; lat = row["Lat"].ToString().ToDouble(); lon = row["Lon"].ToString().ToDouble(); route_id = row["RouteID"].ToString(); trailer_number = row["TrailerID"].ToString(); trackingAssetId = row["AssetID"].ToString(); } } ObjGPS.Dispose(); var json = new JObject() { new JProperty("carrier", new JObject() { new JProperty("fvCarrierId", FVCARRIERID), new JProperty("scac", SCAC) }), new JProperty("location",new JObject() { new JProperty("latitude", lat), new JProperty("longitude", lon) }), new JProperty("telematics",new JObject() { new JProperty("provider", "Direct"), new JProperty("trackingAssetId", trackingAssetId) }), new JProperty("eventDetail",new JObject() { new JProperty("event","LO"), new JProperty("reason","NS"), new JProperty("eventDate",string.Format("{0}{1}",UsuarioActual.FechaActualCliente.ToString("yyyy-MM-ddThh:mm:ss"),"-0500")) }), new JProperty("eventReferences",new JArray() { new JObject() { new JProperty("qualifier", "route_id"), new JProperty("description", ""), new JProperty("value",route_id) }, new JObject() { new JProperty("qualifier", "trailer_number"), new JProperty("description", ""), new JProperty("value",trailer_number) } }) }; return json; } #endregion #region "A P I" private bool EnviarShipmentAPI(string Datos) { bool Retorno = false; string correlationId = GuidGenerator.GenerateTimeBasedGuid(UsuarioActual.FechaActualCliente).ToString(); HttpClient wc = new HttpClient(); try { var Url = new Uri("https://api.freightverify.com/ws/rest/v2/tl/shipment"); var content = new StringContent(Datos, Encoding.UTF8, "application/json"); wc.DefaultRequestHeaders.Add("Authorization", $"Basic {Token}"); wc.DefaultRequestHeaders.Add("WSS-correlationId", correlationId); var response = wc.PostAsync(Url, content).Result; var result = response.Content.ReadAsStringAsync().Result; if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.Created) { if (!string.IsNullOrEmpty(result)) { Retorno = true; } } if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { Retorno = false; var jerror = JObject.Parse(result); Alert(jerror["errors"].ToString(), TipoMensaje.MsgError); } if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { Retorno = false; Alert("No esta autorizado para realizar esta petición.", TipoMensaje.MsgError); } } catch (Exception ex) { Console.WriteLine(ex); } wc.Dispose(); return Retorno; } private bool EnviarEventoAPI(int CveShipment, string Datos) { var ShipmentID = ""; var Customer = ""; var ObjGPS = new ClsGPS(); if (ObjGPS.GetShipments(UsuarioActual.CveCliente, CveShipment)) { if (ObjGPS.DtResultados.Rows.Count == 1) { var row = ObjGPS.DtResultados.Rows[0]; ShipmentID = row["ShipmentID"].ToString(); Customer = row["Customer"].ToString(); } } ObjGPS.Dispose(); string correlationId = GuidGenerator.GenerateTimeBasedGuid(UsuarioActual.FechaActualCliente).ToString(); bool Retorno = false; HttpClient wc = new HttpClient(); try { var fvShipmentId = $"{this.FVCARRIERID}|{Customer}|{ShipmentID}"; var Url = new Uri("https://api.freightverify.com/ws/rest/v2/tl/shipment/event"); var content = new StringContent(Datos, Encoding.UTF8, "application/json"); wc.DefaultRequestHeaders.Add("Authorization", $"Basic {Token}"); wc.DefaultRequestHeaders.Add("WSS-correlationId", correlationId); wc.DefaultRequestHeaders.Add("X-WSS-fvShipmentId", fvShipmentId); var response = wc.PostAsync(Url, content).Result; var result = response.Content.ReadAsStringAsync().Result; if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.Created) { Retorno = true; } if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { Retorno = false; var jerror = JObject.Parse(result); Alert(jerror["errors"].ToString(), TipoMensaje.MsgError); } if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { Retorno = false; Alert("No esta autorizado para realizar esta petición.", TipoMensaje.MsgError); } } catch (Exception ex) { Console.WriteLine(ex); } wc.Dispose(); return Retorno; } private bool EliminarShipmentAPI(int CveShipment) { var ShipmentID = ""; var Customer = ""; var ObjGPS = new ClsGPS(); if (ObjGPS.GetShipments(UsuarioActual.CveCliente, CveShipment)) { if (ObjGPS.DtResultados.Rows.Count == 1) { var row = ObjGPS.DtResultados.Rows[0]; ShipmentID = row["ShipmentID"].ToString(); Customer = row["Customer"].ToString(); } } ObjGPS.Dispose(); string correlationId = GuidGenerator.GenerateTimeBasedGuid(UsuarioActual.FechaActualCliente).ToString(); bool Retorno = false; HttpClient wc = new HttpClient(); try { var fvShipmentId = $"{this.FVCARRIERID}|{Customer}|{ShipmentID}"; var Url = new Uri("https://api.freightverify.com/ws/rest/v2/tl/shipment"); wc.DefaultRequestHeaders.Add("Authorization", $"Basic {Token}"); wc.DefaultRequestHeaders.Add("WSS-correlationId", correlationId); wc.DefaultRequestHeaders.Add("X-WSS-fvShipmentId", fvShipmentId); var response = wc.DeleteAsync(Url).Result; var result = response.Content.ReadAsStringAsync().Result; if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.Created) { Retorno = true; } if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { Retorno = false; var jerror = JObject.Parse(result); Alert(jerror["errors"].ToString(), TipoMensaje.MsgError); } if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { Retorno = false; Alert("No esta autorizado para realizar esta petición.", TipoMensaje.MsgError); } } catch (Exception ex) { Console.WriteLine(ex); } wc.Dispose(); return Retorno; } #endregion protected void BtnAgregarShipment_Click(object sender, EventArgs e) { if (DtStops.Rows.Count < 2) { Alert("Se requieren al menos 2 stops.", TipoMensaje.MsgAdvertencia); return; } var request = GeneraRequestShipment(); bool envio = EnviarShipmentAPI(request.ToString()); if (envio) { bool TieneError = false; var ObjGPS = new ClsGPS(); ObjGPS.IniciaTransacSQL(); try { var CveShipment = ObjGPS.AddShipment(DdlDispositivo.SelectedValue.ToEntero(), true, DdlCustomer.SelectedValue, TxtShipment.Text, TxtAsset.Text, TxtRoute.Text, TxtTrailer.Text.Trim(), TxtObs.Text.Trim(), UsuarioActual.CveCliente); foreach (DataRow row in DtStops.Rows) { if (!ObjGPS.AddStop(CveShipment, row["StopSequence"].ToString().ToEntero(), row["Name"].ToString(), row["LocationID"].ToString(), row["StopType"].ToString(), row["StopRole"].ToString(), row["EarlyArrivalTime"].ToString().ToDateTime(), row["LateArrivalTime"].ToString().ToDateTime(), row["Address"].ToString(), row["City"].ToString(), row["State"].ToString(), row["PostalCode"].ToString(), row["Country"].ToString(), row["Lat"].ToString(), row["Lon"].ToString())) { TieneError = true; } } } catch (Exception ex) { TieneError = true; this.OnError("Ocurrió un error al agregar el shipment", ex); } finally { if (TieneError) { ObjGPS.RollBack(); this.Alert("No se pudo guardar el shipment.", TipoMensaje.MsgError); } else { ObjGPS.Commit(); this.Alert("El shipment se envió correctamente a FreightVerify.", TipoMensaje.MsgInformacion); this.RegistraScript("$('#DivShipment').modal('hide');"); } ObjGPS.Dispose(); CargaDatos(); UpDatos.Update(); } } else { this.Alert("No se pudo enviar el shipment a FreightVerify.", TipoMensaje.MsgError); } } protected void LnkAddEvent_Click(object sender, EventArgs e) { var GvRow = ((sender as LinkButton).NamingContainer as GridViewRow); CveShipment = GvRow.DataKey("CveShipment").ToEntero(); CargaStops(CveShipment); this.RegistraScript("$('#DivEvent').modal({backdrop: 'static', keyboard: false});", "1"); CargaPosicionStop(DdlStops.SelectedValue.ToEntero()); UpEvent.Update(); } private void CargaPosicionStop(int CveStop) { var row = DtStops.FiltroPrimero($"CveStop = {CveStop}"); TxtStopSec.Text = row["StopSequence"].ToString(); TxtLatLongEvent.Text = string.Format("{0},{1}", row["Lat"].ToString(), row["Lon"].ToString()); TxtLatLongEvent.Text = string.Format("{0},{1}", row["Lat"].ToString(), row["Lon"].ToString()); this.RegistraScript($"cargapin('{row["Lat"].ToString()}','{row["Lon"].ToString()}');", "2"); ; } private void CargaStops(int CveShipment) { var ObjGPS = new ClsGPS(); if (ObjGPS.GetStops(CveShipment)) { DtStops = ObjGPS.DtResultados.Copy(); } ObjGPS.Dispose(); DdlStops.DataSource = DtStops; DdlStops.DataBind(); } protected void GvShipments_RowDeleting(object sender, GridViewDeleteEventArgs e) { CveShipment = GvShipments.Rows[e.RowIndex].DataKey("CveShipment").ToEntero(); bool elimino = EliminarShipmentAPI(CveShipment); if (elimino) { var ObjGPS = new ClsGPS(); if (ObjGPS.RemoveShipment(CveShipment)) { Alert("El shipment se eliminó correctamente"); } ObjGPS.Dispose(); } else { this.Alert("No se pudo eliminar el shipment.", TipoMensaje.MsgError); } CargaDatos(); UpDatos.Update(); } protected void GvStops_RowDeleting(object sender, GridViewDeleteEventArgs e) { DtStops.Rows.RemoveAt(e.RowIndex); for (int i = 0; i < DtStops.Rows.Count; i++) { DtStops.Rows[i]["StopSequence"] = i + 1; } GvStops.DataSource = DtStops; GvStops.DataBind(); UpShipment.Update(); } protected void DdlStops_SelectedIndexChanged(object sender, EventArgs e) { CargaPosicionStop(DdlStops.SelectedValue.ToEntero()); UpEvent.Update(); } protected void LnkAddNewEvent_Click(object sender, EventArgs e) { if (CveShipment > 0) { var Request = GeneraRequestEvent(CveShipment).ToString(); bool envio = EnviarEventoAPI(CveShipment, Request); if (envio) { Alert("Se envio el evento correctamente."); this.RegistraScript("$('#DivEvent').modal('hide');"); } else { this.Alert("No se pudo eliminar el shipment.", TipoMensaje.MsgError); } } else { this.Alert("No se pudo eliminar el shipment.", TipoMensaje.MsgError); } } protected void DdlDispositivo_SelectedIndexChanged(object sender, EventArgs e) { if (DdlDispositivo.SelectedValue.ToEntero() > 0) { TxtAsset.Text = DdlDispositivo.SelectedItem.Text.Trim(); } else { TxtAsset.Text = ""; } } protected void GvShipments_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.FCCheckBox("ChkTransmitir").Checked = e.Row.DBCampo("TransmitirTexto") == "Si"; } } protected void ChkTransmitir_CheckedChanged(object sender, EventArgs e) { var check = sender as CheckBox; var GvRow = check.NamingContainer as GridViewRow; CveShipment = GvRow.DataKey("CveShipment").ToEntero(); if (CveShipment > 0) { var ObjGPS = new ClsGPS(); if (ObjGPS.UpdateShipmentTransmision(CveShipment, check.Checked)) { Alert("El estatus de transmisión de datos se actualizó correctamente."); } ObjGPS.Dispose(); } } } namespace Fluent { public enum GuidVersion { TimeBased = 0x01, Reserved = 0x02, NameBased = 0x03, Random = 0x04 } public static partial class GuidGenerator { // number of bytes in guid public const int ByteArraySize = 16; // multiplex variant info public const int VariantByte = 8; public const int VariantByteMask = 0x3f; public const int VariantByteShift = 0x80; // multiplex version info public const int VersionByte = 7; public const int VersionByteMask = 0x0f; public const int VersionByteShift = 4; // indexes within the uuid array for certain boundaries private const byte TimestampByte = 0; private const byte GuidClockSequenceByte = 8; private const byte NodeByte = 10; // offset to move from 1/1/0001, which is 0-time for .NET, to gregorian 0-time of 10/15/1582 private static readonly DateTimeOffset GregorianCalendarStart = new DateTimeOffset(1582, 10, 15, 0, 0, 0, TimeSpan.Zero); // random clock sequence and node public static byte[] DefaultClockSequence { get; set; } public static byte[] DefaultNode { get; set; } static GuidGenerator() { DefaultClockSequence = new byte[2]; DefaultNode = new byte[6]; var random = new Random(); random.NextBytes(DefaultClockSequence); random.NextBytes(DefaultNode); } public static GuidVersion GetVersion(this Guid guid) { byte[] bytes = guid.ToByteArray(); return (GuidVersion)((bytes[VersionByte] & 0xFF) >> VersionByteShift); } public static DateTimeOffset GetDateTimeOffset(Guid guid) { byte[] bytes = guid.ToByteArray(); // reverse the version bytes[VersionByte] &= (byte)VersionByteMask; bytes[VersionByte] |= (byte)((byte)GuidVersion.TimeBased >> VersionByteShift); byte[] timestampBytes = new byte[8]; Array.Copy(bytes, TimestampByte, timestampBytes, 0, 8); long timestamp = BitConverter.ToInt64(timestampBytes, 0); long ticks = timestamp + GregorianCalendarStart.Ticks; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTime GetDateTime(Guid guid) { return GetDateTimeOffset(guid).DateTime; } public static DateTime GetLocalDateTime(Guid guid) { return GetDateTimeOffset(guid).LocalDateTime; } public static DateTime GetUtcDateTime(Guid guid) { return GetDateTimeOffset(guid).UtcDateTime; } public static Guid GenerateTimeBasedGuid() { return GenerateTimeBasedGuid(DateTimeOffset.UtcNow, DefaultClockSequence, DefaultNode); } public static Guid GenerateTimeBasedGuid(DateTime dateTime) { return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode); } public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime) { return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode); } public static Guid GenerateTimeBasedGuid(DateTime dateTime, byte[] clockSequence, byte[] node) { return GenerateTimeBasedGuid(new DateTimeOffset(dateTime), clockSequence, node); } public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime, byte[] clockSequence, byte[] node) { if (clockSequence == null) throw new ArgumentNullException("clockSequence"); if (node == null) throw new ArgumentNullException("node"); if (clockSequence.Length != 2) throw new ArgumentOutOfRangeException("clockSequence", "The clockSequence must be 2 bytes."); if (node.Length != 6) throw new ArgumentOutOfRangeException("node", "The node must be 6 bytes."); long ticks = (dateTime - GregorianCalendarStart).Ticks; byte[] guid = new byte[ByteArraySize]; byte[] timestamp = BitConverter.GetBytes(ticks); // copy node Array.Copy(node, 0, guid, NodeByte, Math.Min(6, node.Length)); // copy clock sequence Array.Copy(clockSequence, 0, guid, GuidClockSequenceByte, Math.Min(2, clockSequence.Length)); // copy timestamp Array.Copy(timestamp, 0, guid, TimestampByte, Math.Min(8, timestamp.Length)); // set the variant guid[VariantByte] &= (byte)VariantByteMask; guid[VariantByte] |= (byte)VariantByteShift; // set the version guid[VersionByte] &= (byte)VersionByteMask; guid[VersionByte] |= (byte)((byte)GuidVersion.TimeBased << VersionByteShift); return new Guid(guid); } } }