text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Text; using OpenTK.Mathematics; using OpenTK.Graphics.OpenGL4; namespace Framework2D.Graphics { public class BatchRenderer { private Shader defaultShader; private Matrix4 projectionMatrix; private Matrix4 viewMatrix; private List<Batch> batches; private bool begin = false; private bool end = true; public int drawCallCount = 0; public BatchRenderer(int width, int height) { defaultShader = new Shader("vUnlit.glsl", "fUnlit.glsl"); projectionMatrix = Matrix4.CreateOrthographicOffCenter(0, width, height, 0, 0.0f, 100f); batches = new List<Batch>(); } public void Begin(Matrix4 viewMatrix) { this.viewMatrix = viewMatrix; Begin(); } public void Begin() { if (begin) throw new Exception("End the batch first"); begin = true; end = false; drawCallCount = 0; } /* * * Texture2D * */ public void Draw(Texture2D texture, Vector2 position, Vector2 scale, float angle, Vector2 origin) { BatchItem item = new BatchItem { Texture = texture, Position = position, Scale = scale, Angle = angle, Origin = origin, TexCoords = new Vector2[] { new Vector2(0.0f, 0.0f), new Vector2(1f, 0.0f), new Vector2(1f, 1f), new Vector2(0.0f, 1f), }, Size = texture.Size }; SubmitBatchItem(item); } public void Draw(Texture2D texture, Vector2 position) { Draw(texture, position, Vector2.One, 0.0f, Vector2.Zero); } public void Draw(Texture2D texture, Vector2 position, Vector2 origin) { Draw(texture, position, Vector2.One, 0.0f, origin); } /* * * SubTexture2D * */ public void Draw(SubTexture2D texture, Vector2 position, Vector2 scale, float angle, Vector2 origin) { BatchItem item = new BatchItem { Texture = texture.Texture, Position = position, Scale = scale, Angle = angle, Origin = origin, TexCoords = texture.TexCoords, Size = texture.Size, }; SubmitBatchItem(item); } private void SubmitBatchItem(BatchItem batchItem) { if (batches.Count == 0) batches.Add(new Batch()); for (int i = 0; i < batches.Count; i++) { if (batches[i].AddItem(batchItem)) { return; } } batches.Add(new Batch()); batches[batches.Count - 1].AddItem(batchItem); } public void End() { if (!begin) throw new Exception("Begin batch first"); GL.Clear(ClearBufferMask.ColorBufferBit); foreach(Batch batch in batches) { batch.Finish(); defaultShader.Use(); defaultShader.SetUniformMat4(projectionMatrix, "projection"); defaultShader.SetUniformMat4(viewMatrix, "view"); batch.BindTextures(defaultShader.GetHandle()); GL.BindVertexArray(batch.VA); GL.DrawElements(BeginMode.Triangles, batch.quadCount * 6, DrawElementsType.UnsignedInt, 0); drawCallCount++; GL.BindVertexArray(0); } begin = false; end = true; viewMatrix = Matrix4.Identity; foreach(Batch b in batches) { b.Reset(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Only active while player is lunging /// Checks to see if it overlaps another player /// If it does, it then sends a raycast to that player to see if it hits a lunge hitbox first, which leads to a clash /// Either calls a clash on its player or death on the targeted enemy /// </summary> public class LungeHitBox : MonoBehaviour { //Reference to PlayerController private PlayerController _pc; // Start is called before the first frame update void Start() { _pc = GetComponentInParent<PlayerController>(); } private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { Debug.Log("Hit player"); PlayerController otherPlayer = other.GetComponent<PlayerController>(); if (otherPlayer.TeamID != _pc.TeamID) { if (otherPlayer.CheckState() == PlayerController.MoveState.Lunging) { Vector3 clashDir = otherPlayer.transform.position - _pc.transform.position; clashDir.Normalize(); _pc.Clash(clashDir); } else { Debug.Log("Player " + otherPlayer.PlayerID); otherPlayer.KillPlayer(); } } } } }
using System; using System.Collections.Generic; using System.Data.Services; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Sparda.Core.Services.Contexts { public class BearerManager : IDisposable { private MainBearerAuthentificationContext _ctx; public BearerManager() { _ctx = new MainBearerAuthentificationContext(); } public async Task<IList<string>> GetRolesAsync(string userId) { List<string> roles = new List<string>(); if (!string.IsNullOrEmpty(userId)) { var user = _ctx.AspNetUser.FirstOrDefault(u => u.Id == userId); if (user != null) { user.AspNetRoles.ToList().ForEach(r => roles.Add(r.Name)); } } return roles; } public void Dispose() { _ctx.Dispose(); } } public class MainBearerAuthentificationContext : Sparda.BearerAuthentificationContext.DAL.V8.d4_m4_y2017_h10_m6_s49.BearerAuthentificationContext { private static bool initialized; public MainBearerAuthentificationContext() : base("AuthContext") { if (!initialized) { initialized = true; try { this.UpdateSchema(); } catch (Exception exception) { } } } } public class MainBearerAuthentificationService : Telerik.OpenAccess.DataServices.OpenAccessDataService<MainBearerAuthentificationContext> { [ChangeInterceptor("AspNetUser")] public void OnChangeService(Sparda.BearerAuthentificationContext.DAL.V8.d4_m4_y2017_h10_m6_s49.AspNetUser aspNetUser, UpdateOperations operations) { var user = HttpContext.Current.User; if (!user.IsInRole(MainServiceProviderContext.AdminRole)) { throw new DataServiceException(400, "Not allowed !"); } } } }
using System; using System.Collections.Generic; using System.Text; namespace DMS.DataAccessObject { /// <summary> /// /// </summary> [Serializable] public class ReportParamEtt { #region Propreties private String _ParamName = String.Empty; private String _ParamType = String.Empty; private Object _ParamValue = String.Empty; public String ParamName { get { return _ParamName; } set { this._ParamName = value; } } public String ParamType { get { return _ParamType; } set { this._ParamType = value; } } public Object ParamValue { get { return _ParamValue; } set { this._ParamValue = value; } } #endregion #region Constructor public ReportParamEtt(String paramName, String paramType, String paramValue) { this._ParamName = paramName; this._ParamType = paramType; this._ParamValue = paramValue; } #endregion } }
using Reactive.Flowable.Subscriber; using System; namespace Reactive.Flowable { public abstract partial class FlowableSourceBase<T> : IFlowable<T> { public virtual IDisposable Subscribe(ISubscriber<T> subscriber) { var s = GetSubscription(subscriber); subscriber.OnSubscribe(s); return s; } protected abstract ISubscription GetSubscription(ISubscriber<T> subscriber); } }
namespace DChild.Databases { public enum WeaponAttackMethod { Melee = 1, Range, _COUNT } }
namespace Airelax.Infrastructure.ThirdPartyPayment.ECPay.Request { public class ECRequestHeader { public long TimeStamp { get; set; } public string Revision { get; set; } } }
#region Using directives using System; using System.Collections.Generic; using System.Text; #endregion namespace Sideris.SiderisServer { internal class ByteParser { private byte[] bytes; private int currentOffset; public ByteParser(byte[] bytes) { this.bytes = bytes; currentOffset = 0; } public int CurrentOffset { get { return currentOffset; } } public ByteString ReadLine() { ByteString line = null; for(int i = currentOffset; i < bytes.Length; i++) { if(bytes[i] == (byte) '\n') { int len = i - currentOffset; if(len > 0 && bytes[i - 1] == (byte) '\r') len--; line = new ByteString(bytes, currentOffset, len); currentOffset = i + 1; return line; } } if(currentOffset < bytes.Length) line = new ByteString(bytes, currentOffset, bytes.Length - currentOffset); currentOffset = bytes.Length; return line; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Entities.Models { [Table("ReportEntry")] public class ReportEntry { public int ID { get; set; } public DateTime CreateDate { get; set; } public DateTime LastMod { get; set; } public DateTime ReportDate { get; set; } [ForeignKey(nameof(Runsheet))] public int RunsheetID { get; set; } public Runsheet Runsheet { get; set; } public int Col { get; set; } public ICollection<ReportDataEntry> ReportDataEntries { get; set; } } }
namespace SubC.Attachments.ClingyEditor { using UnityEditor; using UnityEngine; using System.Linq; using UnityEditorInternal; [CustomEditor(typeof(SpriteParams))] public class SpriteParamsEditor : Editor { ReorderableList framesRL; public static Vector2 GetPositionParam(SpriteParams.SpriteFrame frame, float scale, Vector2 offset) { Vector2 position = Vector2.zero; if (frame.paramList.HasParam(ParamType.Vector3, "position")) position = frame.paramList.GetParam(ParamType.Vector3, "position").vector3Value * frame.sprite.pixelsPerUnit; position.y = -position.y; Vector2 pivot = new Vector2(frame.sprite.pivot.x, frame.sprite.rect.height - frame.sprite.pivot.y); Vector2 handlePos = offset + (pivot + position) * scale; return handlePos; } static void DrawPreviewSprite(SpriteParams.SpriteFrame frame, Sprite previewSprite, Vector2 size, Vector2 offset, bool clip = true) { float scale = size.x / frame.sprite.rect.width; Vector2 position = GetPositionParam(frame, scale, offset); // very simple clipping - would be pretty hard to do it right :/ if (clip && ((position - offset).x > size.x || (position - offset).x < 0 || (position - offset).y > size.y || (position - offset).y < 0)) return; Vector2 previewSize = ClingyEditorUtils.GetSpriteAspectSize(previewSprite, previewSprite.rect.size * scale) * (frame.sprite.pixelsPerUnit / previewSprite.pixelsPerUnit); Vector2 previewPivot = new Vector2(previewSprite.pivot.x, previewSprite.rect.height - previewSprite.pivot.y) * (frame.sprite.pixelsPerUnit / previewSprite.pixelsPerUnit); previewPivot *= scale; bool flipX = false; // if (frame.paramList.HasParam(ParamType.Bool)) // flipX = frame.paramList.GetParam(ParamType.Bool).boolValue; bool flipY = false; // if (frame.paramList.HasParam(ParamType.FlipY)) // flipY = frame.paramList.GetParam(ParamType.FlipY).boolValue; float angle = 0; // if (frame.paramList.HasParam(ParamType.Rotation)) // angle = frame.paramList.GetParam(ParamType.Rotation).quaternionValue.eulerAngles.z; ClingyEditorUtils.DrawTextureGUI(position - previewPivot, previewSprite, previewSize, angle, previewPivot, flipX, flipY); } public static void DrawSpriteAndPreview(SpriteParams.SpriteFrame frame, Sprite previewSprite, Vector2 size, Vector2 offset, bool clip = true) { // assuming all params are local // todo - show a warning that results may vary from the displayed preview? int sortingOffset = 0; // if (frame.paramList.HasParam(ParamType.Integer)) // sortingOffset = frame.paramList.GetParam(ParamType.Integer).intValue; if (sortingOffset >= 0) ClingyEditorUtils.DrawTextureGUI(offset, frame.sprite, size); if (previewSprite != null) DrawPreviewSprite(frame, previewSprite, size, offset, clip: clip); if (sortingOffset < 0) ClingyEditorUtils.DrawTextureGUI(offset, frame.sprite, size); } // Vector2 GetAnchorPos(SerializedProperty spriteAnchorProp, Sprite sprite) { // Vector2 position = spriteAnchorProp.FindPropertyRelative("anchor.position").vector3Value // * sprite.pixelsPerUnit; // position.y = -position.y; // Vector2 pivot = new Vector2(sprite.pivot.x, sprite.rect.height - sprite.pivot.y); // Vector2 handlePos = GetSpritePos(sprite) + (pivot + position) * GetSpriteScale(sprite); // return handlePos; // } // void DrawAnchor(SerializedProperty spriteAnchorProp, Sprite sprite, Vector2 pos) { // Vector2 handlePos = GetAnchorPos(spriteAnchorProp, sprite); // int controlId = GUIUtility.GetControlID("Slider1D".GetHashCode(), FocusType.Keyboard); // GUIStyle handle = new GUIStyle("U2D.pivotDot"); // if (handlePos.x < handle.fixedWidth / 2 || handlePos.x > spriteThumbnailSize.x - handle.fixedWidth / 2 // || handlePos.y < handle.fixedHeight / 2 || handlePos.y > spriteThumbnailSize.x - handle.fixedHeight / 2) // return; // handlePos += pos; // Rect handleRect = new Rect(handlePos.x - handle.fixedWidth / 2, handlePos.y - handle.fixedHeight / 2, // handle.fixedWidth, handle.fixedHeight); // if (Event.current.type == EventType.Repaint) // handle.Draw(handleRect, GUIContent.none, controlId); // } // void CopyAnchor(SerializedProperty spriteAnchorProp) { // string s = string.Format("__ClingyAnchor|{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}", // spriteAnchorProp.FindPropertyRelative("anchor.position").vector3Value.x, // spriteAnchorProp.FindPropertyRelative("anchor.position").vector3Value.y, // spriteAnchorProp.FindPropertyRelative("anchor.position").vector3Value.z, // spriteAnchorProp.FindPropertyRelative("anchor.rotation").quaternionValue.x, // spriteAnchorProp.FindPropertyRelative("anchor.rotation").quaternionValue.y, // spriteAnchorProp.FindPropertyRelative("anchor.rotation").quaternionValue.z, // spriteAnchorProp.FindPropertyRelative("anchor.rotation").quaternionValue.w, // spriteAnchorProp.FindPropertyRelative("anchor.sortingOffset").intValue, // spriteAnchorProp.FindPropertyRelative("anchor.flipX").boolValue, // spriteAnchorProp.FindPropertyRelative("anchor.flipY").boolValue); // EditorGUIUtility.systemCopyBuffer = s; // } // void PasteAnchor(SerializedProperty spriteAnchorProp) { // if (!EditorGUIUtility.systemCopyBuffer.StartsWith("__ClingyAnchor")) // return; // string[] parts = EditorGUIUtility.systemCopyBuffer.Split('|'); // if (parts.Length != 11) // return; // Vector3 v = new Vector3(float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3])); // spriteAnchorProp.FindPropertyRelative("anchor.position").vector3Value = v; // Quaternion q = new Quaternion(float.Parse(parts[4]), float.Parse(parts[5]), float.Parse(parts[6]), // float.Parse(parts[7])); // spriteAnchorProp.FindPropertyRelative("anchor.rotation").quaternionValue = q; // spriteAnchorProp.FindPropertyRelative("anchor.sortingOffset").intValue = int.Parse(parts[8]); // spriteAnchorProp.FindPropertyRelative("anchor.flipX").boolValue = bool.Parse(parts[9]); // spriteAnchorProp.FindPropertyRelative("anchor.flipY").boolValue = bool.Parse(parts[10]); // } void OnEnable() { framesRL = new ReorderableList(serializedObject, serializedObject.FindProperty("frames"), true, true, false, true); framesRL.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "Sprites"); }; framesRL.elementHeightCallback = (int index) => { if (serializedObject.FindProperty("frames").arraySize == 0) return 0; return 60; }; framesRL.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { Vector2 thumbSize = new Vector2(rect.height - 15, rect.height - 15); SpriteParams spriteParams = (SpriteParams) target; SpriteParams.SpriteFrame frame = spriteParams.GetFrame(index); DrawSpriteAndPreview(frame, (Sprite) serializedObject.FindProperty("previewSprite").objectReferenceValue, ClingyEditorUtils.GetSpriteAspectSize(frame.sprite, thumbSize), rect.position); // DrawAnchor(framesProp, sprite, rect.position); float btnWidth = (rect.width) / 3f - thumbSize.x + 20; if (GUI.Button(new Rect(rect.x + 60, rect.y + rect.height / 2 - 11, btnWidth, 20), "Edit")) { serializedObject.FindProperty("frameToEdit").intValue = index; ShowEditor(); } // if (GUI.Button(new Rect(rect.x + 60 + btnWidth + 5, rect.y + rect.height / 2 - 11, btnWidth, 20), // "Copy")) { // // CopyAnchor(framesProp); // } // if (GUI.Button(new Rect(rect.x + 60 + btnWidth * 2 + 10, rect.y + rect.height / 2 - 11, btnWidth, 20), // "Paste")) { // // PasteAnchor(framesProp); // } }; } void ShowEditor() { SpriteParamsWindow.Init(); Selection.activeObject = target; } public override void OnInspectorGUI() { serializedObject.Update(); SpriteParams spriteParams = (SpriteParams) target; Event evt = Event.current; Rect drop_area = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true)); var style = new GUIStyle("box"); if (EditorGUIUtility.isProSkin) style.normal.textColor = Color.white; // thanks to ProCamera2D for the idea - Unity does not provide any simple way to select multiple assets // and add them to a reorderable list, but drag/drop works well GUI.Box(drop_area, "\nAdd sprites by dragging them here!", style); switch (evt.type) { case EventType.DragUpdated: case EventType.DragPerform: if (!drop_area.Contains(evt.mousePosition)) break; DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (evt.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); foreach (Object obj in DragAndDrop.objectReferences) { Sprite[] sprites = new Sprite[0]; if (obj is Texture2D) { Texture2D tex = (Texture2D) obj; string spriteSheet = AssetDatabase.GetAssetPath(tex); sprites = AssetDatabase.LoadAllAssetsAtPath(spriteSheet).OfType<Sprite>().ToArray(); } else if (obj is Sprite) { sprites = new Sprite[] { obj as Sprite }; } else if (obj is GameObject) { GameObject go = (GameObject) obj; SpriteRenderer sr = go.GetComponent<SpriteRenderer>(); if (sr && sr.sprite) sprites = new Sprite[] { sr.sprite }; } foreach (Sprite s in sprites) spriteParams.AddFrame(s); } } break; } EditorGUILayout.Space(); framesRL.DoLayoutList(); serializedObject.ApplyModifiedProperties(); } } }
using System.Drawing; using BizService.Common; using IWorkFlow.BaseService; using IWorkFlow.DataBase; using IWorkFlow.Host; using IWorkFlow.OfficeService.OpenXml; using IWorkFlow.ORM; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace BizService.Services { public class B_OA_TravelSvc : BaseDataHandler { public DataTable mPrintTable = new DataTable(); [DataAction("GetData", "userid", "caseid", "baid", "actid")] public object GetData(string userid, string caseId, string baid, string actid) { try { //判断是否为传阅 if (!String.IsNullOrEmpty(actid)) { //只有待办箱才有设置为已读 if (!String.IsNullOrEmpty(baid)) engineAPI.SetIsReaded(caseId, baid, userid); } GetDataModel data = new GetDataModel(); B_OA_TravelList en = new B_OA_TravelList(); en.Condition.Add("caseId=" + caseId); data.baseInfo = Utility.Database.QueryObject<B_OA_TravelList>(en); if (data.baseInfo == null) { DeptInfoAndUserInfo d_u_Infor = ComClass.GetDeptAndUserByUserId(userid); var baseInfo = new B_OA_TravelList(); baseInfo.travelerName = d_u_Infor.userinfo.CnName; baseInfo.dpname = d_u_Infor.deptinfo.DPName; baseInfo.travelNames = d_u_Infor.userinfo.CnName + ";"; baseInfo.travelDps = d_u_Infor.deptinfo.DPName + ";"; baseInfo.travelIds = userid + ";"; ; data.baseInfo = baseInfo; } else { DeptInfoAndUserInfo d_u_Infor = ComClass.GetDeptAndUserByUserId(data.baseInfo.traveler); data.baseInfo.travelerName = d_u_Infor.userinfo.CnName; data.baseInfo.dpname = d_u_Infor.deptinfo.DPName; } return data; } catch (Exception ex) { ComBase.Logger(ex); throw (new Exception("获取数据失败!", ex)); } } ////保存 //[DataAction("save", "BizParams", "userid", "content")] //public string Save(string BizParams, string userid, string content) //{ // SkyLandDeveloper developer = new SkyLandDeveloper(BizParams, userid, tran); // IDbTransaction tran = Utility.Database.BeginDbTransaction(); // try // { // SaveDataModel data = JsonConvert.DeserializeObject<SaveDataModel>(content); // string caseid = developer.caseid;//获取业务流ID // if (caseid == null || caseid.Equals("")) // { // caseid = developer.Create();//生成一个业务流ID // } // SaveData(data, tran, caseid);//保存 // developer.Commit();//提交事务 // var retContent = GetData(userid, caseid); // return JsonConvert.SerializeObject( retContent); // } // catch (Exception ex) // { // developer.RollBack();//回滚事务 // ComBase.Logger(ex);//写日专到本地文件 // return Utility.JsonMsg(false, "保存失败:" + ex.Message.Replace(":", " ")); // } //} //保存数据 public void SaveData(SaveDataModel data, IDbTransaction tran, string caseId) { if (caseId != null) data.baseInfo.caseId = caseId; data.baseInfo.Condition.Add("caseId=" + data.baseInfo.caseId); //更新或插入主业务信息 if (Utility.Database.Update<B_OA_TravelList>(data.baseInfo, tran) < 1) { Utility.Database.Insert<B_OA_TravelList>(data.baseInfo, tran); SaveTravelRaletive(data.baseInfo.travelIds, caseId, tran); } } //发送 [DataAction("send", "BizParams", "userid", "content")] public string Send(string BizParams, string userid, string content) { IDbTransaction tran = Utility.Database.BeginDbTransaction(); SkyLandDeveloper developer = new SkyLandDeveloper(BizParams, userid, tran); try { SaveDataModel data = JsonConvert.DeserializeObject<SaveDataModel>(content); string caseid = developer.caseid; if (String.IsNullOrEmpty(caseid)) { data.baseInfo.traveler = userid; data.baseInfo.travelStatus = "1"; developer.caseName = ComClass.GetUserInfo(userid).CnName + "-出差申请"; caseid = developer.Create(); } else { data.baseInfo.travelStatus = "2"; } SaveData(data, tran, caseid); developer.Send(); developer.Commit(); return Utility.JsonMsg(true, "发送成功!"); } catch (Exception ex) { Utility.Database.Commit(tran); ComBase.Logger(ex); throw (new Exception("业务发送失败!", ex)); } } /// <summary> /// 出差人员关系表 /// </summary> /// <param name="travelIds">出差人员</param> /// <param name="caseId"></param> /// <param name="tran"></param> public void SaveTravelRaletive(string travelIds, string caseId, IDbTransaction tran) { if (!String.IsNullOrEmpty(caseId)) { DataRowMap rm = new DataRowMap(); rm.TableName = "B_OA_WorkFlow_UserId_R"; rm.Condition.Add("caseId=" + caseId); Utility.Database.Delete(rm, tran); string[] array = travelIds.Split(';'); for (int i = 0; i < array.Length - 1; i++) { DataRowMap add = new DataRowMap(); add.TableName = "B_OA_WorkFlow_UserId_R"; add.Fields.Add(new FieldInfo("userid", array[i])); add.Fields.Add(new FieldInfo("caseId", caseId)); Utility.Database.Insert(add, tran); } } } /// <summary> /// 获取会议数据 /// </summary> /// <param name="userid">当前用户ID</param> /// <returns>返回json数据结果</returns> [DataAction("SearchDate", "startTime", "endTime", "travelStatus", "travelerName", "dpname", "userid")] public string SearchDate(string startTime, string endTime, string travelStatus, string travelerName, string dpname, string userid) { StringBuilder strSql = new StringBuilder(); GetDataModel dataModel = new GetDataModel(); strSql.Append(String.Format(@"SELECT id, caseId,CONVERT(VARCHAR(10),travelStartTime,120) AS travelStartTime, CONVERT(VARCHAR(10),travelEndTime,120) AS travelEndTime, DATEDIFF(DAY,travelStartTime,travelEndTime) AS totalDays, travelStartTime1_sj, travelEndTime1_sj, totalDays1_sj, traveler, travelAddress, travelFee, remark, travelReason, travelStatus,B.CnName AS travelerName, C.FullName AS dpname,(CASE WHEN A.travelStatus = 1 THEN '待审批' WHEN (A.travelStatus = 2 AND A.travelStartTime > GETDATE()) THEN '已审批' WHEN (A.travelStatus = 2 AND A.travelStartTime < GETDATE() AND A.travelEndTime > GETDATE()) THEN '出差中' ELSE '已结束' END) AS StatusText FROM B_OA_TravelList A LEFT JOIN FX_UserInfo B ON A.traveler = B.UserID LEFT JOIN FX_Department C ON B.DPID = C.DPID WHERE A.travelStartTime >= '{0}' AND A.travelEndTime <= '{1}' AND (C.FullName = '{4}' OR '{4}' = '') AND (A.travelStatus = '{2}' OR ('{2}' = '' AND A.travelEndTime < '{1}') OR ('{2}' = '')) AND B.CnName LIKE '%{3}%' ", startTime, endTime, travelStatus, travelerName, dpname)); DataSet dataSet = Utility.Database.ExcuteDataSet(strSql.ToString()); string jsonData = JsonConvert.SerializeObject(dataSet.Tables[0]); dataModel.list = (List<B_OA_TravelList>)JsonConvert.DeserializeObject(jsonData, typeof(List<B_OA_TravelList>)); if (dataModel.baseInfo == null) { dataModel.baseInfo = new B_OA_TravelList(); } return JsonConvert.SerializeObject(dataModel); } [DataAction("GetTravelGrid","isEnd","top","handler", "userid")] public object GetTravelGrid(string isEnd,string top,string handler,string userid) { var tran = Utility.Database.BeginDbTransaction(); try { //条件 StringBuilder condition = new StringBuilder(); string topCondtion = ""; if (!string.IsNullOrEmpty(top)) { topCondtion = "top " + top; } if (!string.IsNullOrEmpty(isEnd)) { condition.AppendFormat(" and fc.isEnd = '1'"); } //判断用户的权限,可修改哪些范围的数据。用于在综合管理读取的数据并做修改,综合查询无需设置handler。 if (!string.IsNullOrEmpty(handler)) { //判断权限 string priName = CommonFunctional.JudgeMan(userid, tran); //全局权限 if (priName == "all") { condition.AppendFormat(""); } else if (priName == "dep")//部门权限 { condition.AppendFormat(" and b.DPID = '{0}'", ComClass.GetUserInfo(userid).DPID); } else if (priName == "single")//个权限 { condition.AppendFormat(" and b.UserId = '{0}'", userid); } } StringBuilder strSql = new StringBuilder(); strSql.AppendFormat(@" select {0} caseId,travelReason,b.CnName,travelAddress,travelStartTime,travelEndTime,travelNames from B_OA_TravelList as a LEFT JOIN FX_UserInfo as b on a.traveler = b.UserID LEFT JOIN FX_WorkFlowCase as fc on a.caseId = fc.ID where 1=1 {1} order By caseId desc ", topCondtion, condition.ToString()); DataSet ds = Utility.Database.ExcuteDataSet(strSql.ToString(), tran); DataTable dataTable = ds.Tables[0]; Utility.Database.Commit(tran); return new { dataTable = dataTable }; } catch (Exception ex) { Utility.Database.Rollback(tran); ComBase.Logger(ex); throw (new Exception("读取失败!", ex)); } } [DataAction("GetTravelByCaseId", "caseid")] public object GetTravelByCaseId(string caseid) { var tran = Utility.Database.BeginDbTransaction(); try { B_OA_TravelList baseInfor = new B_OA_TravelList(); baseInfor.Condition.Add("caseId = " + caseid); baseInfor = Utility.Database.QueryObject<B_OA_TravelList>(baseInfor, tran); DeptInfoAndUserInfo d_u_Infor = ComClass.GetDeptAndUserByUserId(baseInfor.traveler); baseInfor.travelerName = d_u_Infor.userinfo.CnName; baseInfor.dpname = d_u_Infor.deptinfo.DPName; Utility.Database.Commit(tran); return new { baseInfor = baseInfor }; } catch (Exception ex) { Utility.Database.Rollback(tran); ComBase.Logger(ex); throw (new Exception("获取数据失败!", ex)); } } [DataAction("SaveData", "jsonData")] public object SaveData(string jsonData) { var tran = Utility.Database.BeginDbTransaction(); B_OA_TravelList data = JsonConvert.DeserializeObject<B_OA_TravelList>(jsonData); try { if (!string.IsNullOrEmpty(data.caseId)) { data.Condition.Add("caseId = " + data.caseId); Utility.Database.Update<B_OA_TravelList>(data, tran); } Utility.Database.Commit(tran); bool b = true; return new { }; } catch (Exception ex) { Utility.Database.Rollback(tran); ComBase.Logger(ex); throw (new Exception("保存失败!", ex)); } } [DataAction("DeleteData", "caseId", "userid")] public object DeleteData(string caseId, string userid) { IDbTransaction tran = Utility.Database.BeginDbTransaction(); try { if (!string.IsNullOrEmpty(caseId)) { B_OA_TravelList data = new B_OA_TravelList(); data.Condition.Add("caseId=" + caseId); Utility.Database.Delete(data, tran); //删除相关业务,业务办结不可删除 CommonFunctional.DeleteWorkFlowCase(caseId, userid, tran); Utility.Database.Commit(tran); } else { throw (new Exception("删除数据失败")); } bool b = true; return new { }; } catch (Exception ex) { ComBase.Logger(ex); throw (new Exception("删除失败!", ex)); } } #region 打印 [DataAction("PrintDoc", "caseid", "userid")] public object PrintDoc(string caseid, string userid) { var tran = Utility.Database.BeginDbTransaction(); try { string wordPath = CommonFunctional.GetDocumentPathByName("Travel", "FileModelDir"); string targetpath = CommonFunctional.GetDocumentPathByName("Travel", "FileDir"); targetpath = targetpath + "出差申请" + caseid + ".docx"; wordPath = wordPath + "出差申请.docx"; var dic = CreateWordSendDocData(caseid, tran); IWorkFlow.OfficeService.IWorkFlowOfficeHandler.ProduceWord2007UP(wordPath, targetpath, dic); Utility.Database.Commit(tran); foreach (var item in dic) { if (item.Value is Image) { var img = item.Value as Image; img.Dispose(); } } return new { targetpath = targetpath }; } catch (Exception ex) { ComBase.Logger(ex); return Utility.JsonMsg(false, "打印失败:" + ex.Message.Replace(":", " ")); } } /// <summary> /// 创建一个Word数据 /// </summary> /// <param name="caseid"></param> /// <returns></returns> private Dictionary<string, Object> CreateWordSendDocData(string caseid, IDbTransaction tran) { //创建内容 Dictionary<string, Object> dict = new Dictionary<string, Object>(); B_OA_TravelList en = new B_OA_TravelList(); en.Condition.Add("caseId=" + caseid); en = Utility.Database.QueryObject<B_OA_TravelList>(en); DeptInfoAndUserInfo d_u_Infor = ComClass.GetDeptAndUserByUserId(en.traveler); en.travelerName = d_u_Infor.userinfo.CnName; en.dpname = d_u_Infor.deptinfo.DPName; dict.Add("travelDps", en.travelDps == null ? "" : en.travelDps); dict.Add("travelAddress", en.travelAddress == null ? "" : en.travelAddress); dict.Add("travelReason", en.travelReason == null ? "" : en.travelReason); dict.Add("carStatus", en.carStatus == null ? "" : en.carStatus); dict.Add("remark", en.remark == null ? "" : en.remark); if (!string.IsNullOrEmpty(en.ortherMan)) { en.travelNames = en.travelNames + en.ortherMan; } dict.Add("travelNames", en.travelNames == null ? "" : en.travelNames); string startTime = ""; if (!string.IsNullOrEmpty(en.travelStartTime.ToString())) { startTime = (DateTime.Parse(en.travelStartTime.ToString())).ToString("yyyy年MM月dd日 hh:mm"); } string endTime = ""; if (!string.IsNullOrEmpty(en.travelEndTime.ToString())) { endTime = (DateTime.Parse(en.travelEndTime.ToString())).ToString("yyyy年MM月dd日 hh:mm"); } dict.Add("travelStartTime", startTime); dict.Add("travelEndTime", endTime); //获取所有评阅意见 FX_WorkFlowBusAct work = new FX_WorkFlowBusAct(); work.Condition.Add("CaseID = " + caseid); work.OrderInfo = "ReceDate asc"; List<FX_WorkFlowBusAct> listWork = Utility.Database.QueryList<FX_WorkFlowBusAct>(work, tran); //将所有工作流信息格式化 List<B_OA_PrintParagragh> listPara = CommonFunctional.ChangeListToMatch(listWork); //室主任意见 List<B_OA_PrintParagragh> szrSugList = new List<B_OA_PrintParagragh>(); //站领导意见 List<B_OA_PrintParagragh> zldSugList = new List<B_OA_PrintParagragh>(); int k = 0; //室主任意见 for (k = 0; k < listPara.Count; k++) { if (listPara[k].ActID == "A002") { szrSugList.Add(listPara[k]); } else if (listPara[k].ActID == "A003") { zldSugList.Add(listPara[k]); } } //室主任意见 var imgSzrSugList = new OpenXmlHelper.ImageTextArray[szrSugList.Count]; for (k = 0; k < szrSugList.Count; k++) { imgSzrSugList[k] = new OpenXmlHelper.ImageTextArray(); imgSzrSugList[k].Images = szrSugList[k].Image; imgSzrSugList[k].Text = szrSugList[k].Text; imgSzrSugList[k].Foots = szrSugList[k].Foots; imgSzrSugList[k].FootAlign = DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Right; } dict.Add("szrSug", imgSzrSugList); //站领导意见 var imgZldSugList = new OpenXmlHelper.ImageTextArray[zldSugList.Count]; for (k = 0; k < zldSugList.Count; k++) { imgZldSugList[k] = new OpenXmlHelper.ImageTextArray(); imgZldSugList[k].Images = zldSugList[k].Image; imgZldSugList[k].Text = zldSugList[k].Text; imgZldSugList[k].Foots = zldSugList[k].Foots; imgZldSugList[k].FootAlign = DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Right; } dict.Add("zldSug", imgZldSugList); return dict; } #endregion // 获取数据模型 public class GetDataModel { public B_OA_TravelList baseInfo; public List<B_OA_TravelList> list; public List<B_OA_Sighture> handWriteList; public B_OA_TravelList DetailEdit = new B_OA_TravelList(); } /// <summary> /// 保存数据模型 /// </summary> public class SaveDataModel { public B_OA_TravelList baseInfo; public KOGridEdit<B_OA_TravelList> list; } public override string Key { get { return "B_OA_TravelSvc"; } } } }
using ArcOthelloBG.Logic; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace ArcOthelloBG { class OthelloFileManager { public static void SaveToFile(string filename, OthelloState state) { IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, state); stream.Close(); } public static OthelloState LoadStateFromFile(string filename) { IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); OthelloState state = (OthelloState)formatter.Deserialize(stream); stream.Close(); return state; } } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DRL_2021.Menus { class TitleUI : Menu { public SceneTitle Scene; SubMenuHandler<TitleMenu> TitleMenu = new SubMenuHandler<TitleMenu>() { BlocksInput = true, InputPriority = 10 }; public SubMenuHandler<Menu> SubMenu = new SubMenuHandler<Menu>() { BlocksInput = true }; protected override IEnumerable<IMenuArea> MenuAreas => Enumerable.Empty<IMenuArea>(); protected override IEnumerable<SubMenuHandler> SubMenuHandlers => new SubMenuHandler[] { TitleMenu, SubMenu }; public override FontRenderer FontRenderer => Scene.FontRenderer; public TitleUI(SceneTitle scene) { Scene = scene; } public override void Update(Scene scene) { base.Update(scene); if (Scene.TitleSM.CurrentState == TitleState.Finish && !TitleMenu.IsOpen) TitleMenu.Open(new TitleMenu(this)); } public override void Draw(Scene scene) { TitleMenu.Draw(scene); SubMenu.Draw(scene); } } class TitleMenu : MenuActNew { public TitleMenu(TitleUI ui) : base(ui.Scene, null, new Vector2(ui.Scene.Viewport.Width / 2, ui.Scene.Viewport.Height * 3 / 4), SpriteLoader.Instance.AddSprite("content/ui_box"), SpriteLoader.Instance.AddSprite("content/ui_gab"), 256, 16 * 10) { var formatName = new TextFormatting() { Bold = true, }; Add(new ActActionNew((builder) => { builder.StartLine(LineAlignment.Center); builder.AppendText("New Game", formatName); builder.NewLine(); builder.AppendText("Starts a new game", FormatDescription); builder.EndLine(); }, () => { ui.Scene.NewGame(); })); Add(new ActActionNew((builder) => { builder.StartLine(LineAlignment.Center); builder.AppendText("Options", formatName); builder.NewLine(); builder.AppendText("Change game settings", FormatDescription); builder.EndLine(); }, () => { ui.SubMenu.Open(new OptionsMenu(ui.Scene)); })); Add(new ActActionNew((builder) => { builder.StartLine(LineAlignment.Center); builder.AppendText("Statistics", formatName); builder.NewLine(); builder.AppendText("View statistics", FormatDescription); builder.EndLine(); }, () => { ui.SubMenu.Open(new StatMenu(ui.Scene)); })); /*Add(new ActActionNew((builder) => { builder.StartLine(LineAlignment.Center); builder.AppendText("Discord", formatName); builder.NewLine(); builder.AppendText("Join our Discord", FormatDescription); builder.EndLine(); }, () => { Process.Start("https://discord.com/invite/J4bn3FG"); })); Add(new ActActionNew((builder) => { builder.StartLine(LineAlignment.Center); builder.AppendText("Github", formatName); builder.NewLine(); builder.AppendText("Report an issue", FormatDescription); builder.EndLine(); }, () => { Process.Start("https://github.com/DaedalusGame/7DRL_2021"); }));*/ Add(new ActActionNew((builder) => { builder.StartLine(LineAlignment.Center); builder.AppendText("Quit", formatName); builder.NewLine(); builder.AppendText("Exits to desktop", FormatDescription); builder.EndLine(); }, () => { ui.Scene.Quit(); })); } } }
using System; using System.Linq; namespace Generics_7 { class ArrayList { public object[] MyArray; public int Size { get; private set; } //public int Capasity { get; set; } public ArrayList() { MyArray = new object[] { }; Size = 0; } public object this[int i] { get { return MyArray[i]; } set { MyArray[i] = value; } } public ArrayList(object[] obj) { MyArray = obj; Size = obj.Count(); } public void Add(object obj) { Array.Resize<object>(ref MyArray, ++Size); MyArray[Size - 1] = obj; } public void Clear() { MyArray = new object[] { }; Size = 0; } public void Reverse() { int size = Size; object[] array = new object[Size]; object[] temp = MyArray; int index = Size - 1; int i = 0; /*for(int i=0;i<Size;i++) { MyArray[--index] = temp[i]; }*/ while (index >= 0) { array[index--] = temp[i++]; } //MyArray[0]=temp[] MyArray = array; } public object[] CopyTo(int from) { int temp = from; if (temp > 0 && temp < Size) { int newSize = Size - from; object[] To = new object[newSize]; for (int i = 0; i < newSize; i++) { To[i] = MyArray[temp]; temp++; } return To; } else return null; } public void AddRange(object[] range) { int temp = this.Size; int index = 0; int tempt = Size + range.Count(); Array.Resize<object>(ref MyArray, tempt); this.Size += range.Count(); for (int i = temp; i < Size; i++) { MyArray[i] = range[index++]; } } public void Remove(int rem) { int index = rem; for (int i = index; i < MyArray.Count() - 1; i++) { MyArray[i] = MyArray[i + 1]; } Array.Resize<object>(ref MyArray, --Size); } } class Program { static void Main(string[] args) { ArrayList myarr = new ArrayList(new object[] { "new interface", 12, 17, 'a' }); Console.WriteLine("ArrayList after creating and filling:"); for (int i = 0; i < myarr.Size; i++) { Console.WriteLine(myarr[i]); } myarr.Clear(); myarr.AddRange(new object[] { 'b', 13, 42, "Kotlin" }); Console.WriteLine("ArrayList after clearing and adding range:"); for (int i = 0; i < myarr.Size; i++) { Console.WriteLine(myarr[i]); } myarr.Remove(1); Console.WriteLine("After removing element with index 1:"); for (int i = 0; i < myarr.Size; i++) { Console.WriteLine(myarr[i]); } myarr.Reverse(); Console.WriteLine("After revercing:"); for (int i = 0; i < myarr.Size; i++) { Console.WriteLine(myarr[i]); } object[] arr = new object[] { }; arr = myarr.CopyTo(1); Console.WriteLine("Copying ArrayList into array of objects from 1 index:"); for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } Console.ReadKey(); } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using ImgLib; namespace PlainServer { internal class ServerTcp { private int PORT; // integer der bruges til id på billeder der modtages private static int filenNum = 0; public ServerTcp(int port) { this.PORT = port; } public void Start() { TcpListener thisServer = new TcpListener(IPAddress.Any, PORT); thisServer.Start(); while (true) { TcpClient socket = thisServer.AcceptTcpClient(); Task.Run(() => { TcpClient tempSocket = socket; DoClient(socket); }); } } private void DoClient(TcpClient socket) { //Starter et stream på det givne netværk NetworkStream clientStream = socket.GetStream(); // Filestream der laver en ny film på den angivet sti FileStream fs = (File.Create( @"C:\Users\mahdi\Sync\DATAMATIKER\3 Semester\3SemesterPROJEKT\PicSecureRest\imgFiles\imgFile" + filenNum++ + ".jpg")); int count; // Buffer til at modtage billeder. Et array af bytes, der kan tage 2048 bytes af gangen byte[] imgBuffer = new byte[2048]; while (socket.Connected) { // variabel der tæller antal bytes. Tager b.la. buffer som parameter count = clientStream.Read(imgBuffer, 0, 2000); // Variabel af Filestream, skriver bytes ud, så man ender med at have et billede. fs.Write(imgBuffer, 0, count); } fs.Close(); } } }
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("IzBone.Common.Editor")] [assembly: InternalsVisibleTo("IzBone.Common.Test")] [assembly: InternalsVisibleTo("IzBone.IzBCollider")] [assembly: InternalsVisibleTo("IzBone.IzBCollider.Editor")] [assembly: InternalsVisibleTo("IzBone.PhysCloth")] [assembly: InternalsVisibleTo("IzBone.PhysCloth.Editor")] [assembly: InternalsVisibleTo("IzBone.PhysSpring")] [assembly: InternalsVisibleTo("IzBone.PhysSpring.Editor")] [assembly: InternalsVisibleTo("IzBone.SimpleRig")] [assembly: InternalsVisibleTo("IzBone.SimpleRig.Editor")]
using System.Collections; using System.Collections.Generic; using UnityEngine; public class enemyFlightPath : MonoBehaviour { public Transform firePointTransform; public float speed; //bullet velocity multiplier public Rigidbody2D rb; private Vector2 direction; private Vector2 normalizedDirection; public GameObject explosionPrefab; private Collider2D thisCollider; public int Damage; private GameObject UserInterface; // Start is called before the first frame update void Start() { UserInterface = GameObject.Find("/Canvas/Image/Slider/Fill Area/expBar"); Vector2 direction = this.transform.up; thisCollider = gameObject.GetComponent<Collider2D>(); normalizedDirection = direction / Mathf.Sqrt(Mathf.Pow (direction.x, 2) + Mathf.Pow (direction.y , 2) ) ; firePointTransform = this.transform.parent.gameObject.transform; this.transform.position = firePointTransform.position; this.transform.rotation = firePointTransform.rotation; } void FixedUpdate() { rb.velocity = normalizedDirection*speed; } void OnCollisionEnter2D (Collision2D other) { if (other.collider.CompareTag("Enemy") || other.collider.CompareTag("Radius") || other.collider.CompareTag("Bullet")) { Physics2D.IgnoreCollision(thisCollider, other.collider); } else if (other.collider.CompareTag("Wall")) { Destroy(gameObject); Instantiate(explosionPrefab, this.transform.position, this.transform.rotation); } else { Destroy(gameObject); Instantiate(explosionPrefab, this.transform.position, this.transform.rotation); UserInterface.SendMessage("addExperience",-1*Damage); } } }
using System; using System.Collections.Generic; using System.Text; namespace Task_1_2._0_ { class Square { public void square(int s) // C большой буквы { try { Console.Clear(); Console.Write("Enter square size: "); int size = Convert.ToInt32(Console.ReadLine()); for (int i = 1; i < (size + 1); i++) { for (int j = 0; j < size; j++) { Console.SetCursorPosition(j, i); Console.WriteLine("+"); } } } catch { Console.Clear(); Console.WriteLine("Enter a number !!!"); } Console.ReadLine(); } } }
using BPI_WebScrapeTask.Classes; using BPI_WebScrapeTask.ClassObjects; using System.Collections.Generic; using System.Linq; using System.Windows; namespace BPI_WebScrapeTask.Controller { /// <summary> /// Class for routing between the views and models. Also performs exception handling. /// </summary> public class MainViewModel { private List<GoogleResult> MergedResults; public void ImportIntoCsv() { if (MergedResults != null) { var csv = new Csv(); csv.SaveData(MergedResults); MessageBox.Show("Saved to CSV in Bin/Debug folder"); } else { MessageBox.Show("Data is yet to be loaded"); } } public List<GoogleResult> GatherSearchResults(bool googleApiChoice) { var api = new GoogleSearch(); var eilishResults = new List<GoogleResult>(); var grandeResults = new List<GoogleResult>(); var mendesResults = new List<GoogleResult>(); if (googleApiChoice) { eilishResults = api.GetSearchResults("Billie Eilish - Therefore I am"); if (eilishResults.Count > 0) //Prevent multiple dialog boxes from appearing { grandeResults = api.GetSearchResults("Ariana Grande - Positions"); mendesResults = api.GetSearchResults("Shawn Mendes - Monster"); } } else { eilishResults = api.GetGoogleApiResults("Billie Eilish - Therefore I am"); grandeResults = api.GetGoogleApiResults("Ariana Grande - Positions"); mendesResults = api.GetGoogleApiResults("Shawn Mendes - Monster"); } MergedResults = eilishResults.Union(grandeResults).Union(mendesResults).ToList(); return MergedResults; } } }
using RRExpress.Common; using System; using System.Globalization; using Xamarin.Forms; namespace RRExpress.AppCommon.Converters { public class EnumDescConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return ""; else { return EnumHelper.GetDescription((Enum)value); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; namespace Apache.Shiro.Authc { public class SuccessfulLoginEventArgs : LoginEventArgs { private IAuthenticationInfo _info; public SuccessfulLoginEventArgs(IAuthenticationToken token, IAuthenticationInfo info) : base(token) { if (info == null) { throw new ArgumentNullException("info"); } _info = info; } public IAuthenticationInfo Info { get { return _info; } } } public delegate void SuccessfulLoginEventHandler(object sender, SuccessfulLoginEventArgs e); }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using System; using System.Runtime.Remoting.Proxies; using System.Runtime.Remoting.Messaging; using FiiiCoin.Utility; using System.Windows; using FiiiCoin.Wallet.Win.Models; using System.Threading.Tasks; using System.Threading; namespace FiiiCoin.Wallet.Win.Common.Proxys { class LogProxy<T> : RealProxy { private T _target; public LogProxy(T target) : base(typeof(T)) { this._target = target; } public override IMessage Invoke(IMessage msg) { IMethodCallMessage callMessage = (IMethodCallMessage)msg; //PreProceede(callMessage); //AutoResetEvent autoResetEvent = new AutoResetEvent(false); object returnResult = null; var task = Task.Factory.StartNew(() => { try { returnResult = callMessage.MethodBase.Invoke(this._target, callMessage.Args); } catch (Exception ex) { Logger.Singleton.Error(string.Format("Error Method in {0}", callMessage.MethodName)); Logger.Singleton.Error(ex.ToString()); } }); Task.WaitAll(task); if (returnResult is Result) { var result = returnResult as Result; PostProceede(callMessage.MethodName, result); } return new ReturnMessage(returnResult, new object[0], 0, null, callMessage); } public void PreProceede(IMethodCallMessage msg) { var methodName = msg.MethodName; Application.Current.Dispatcher.Invoke(() => { Logger.Singleton.Info(methodName); }); } public void PostProceede(string methodName, Result result) { if (result == null) return; if (result.ApiResponse == null || result.ApiResponse.Result == null) return; Application.Current.Dispatcher.Invoke(() => { if (result.ApiResponse.HasError) { Logger.Singleton.InfoFormat("Method({0}) ErrorCode = {1} , ErrorMessage = {2}", methodName, result.ApiResponse.Error.Code, result.GetErrorMsg()); } else { var receiveContent = result.ApiResponse.Result.ToString(); Logger.Singleton.InfoFormat("Method({0}) Result = {1}", methodName, receiveContent.Replace("\r\n", "")); } }); } } //TransparentProxy public static class TransparentProxy { public static T Create<T>() { T instance = Activator.CreateInstance<T>(); LogProxy<T> realProxy = new LogProxy<T>(instance); T transparentProxy = (T)realProxy.GetTransparentProxy(); return transparentProxy; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using DevExpress.XtraEditors; using IRAP.Global; using IRAP.Client.User; using IRAP.Entity.SSO; using IRAP.Entity.Kanban; using IRAP.WCF.Client.Method; namespace IRAP.Client.SubSystems { public partial class frmSelectOptions : IRAP.Client.Global.frmCustomBase { private static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; public frmSelectOptions() { InitializeComponent(); } private void frmSelectOptions_Load(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { if (AvailableProcesses.Instance.Processes.Count <= 0) AvailableProcesses.Instance.GetProcesses( IRAPUser.Instance.CommunityID, IRAPUser.Instance.SysLogID); lstProcesses.DataSource = AvailableProcesses.Instance.Processes; lstProcesses.DisplayMember = "T120NodeName"; lstProcesses.SelectedIndex = AvailableProcesses.Instance.IndexOf( CurrentOptions.Instance.Process); } catch (Exception error) { XtraMessageBox.Show( error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void lstProcesses_SelectedIndexChanged(object sender, EventArgs e) { lstWorkUnits.Items.Clear(); if (lstProcesses.SelectedItem != null) { ProcessInfo process = AvailableProcesses.Instance.Processes[lstProcesses.SelectedIndex]; try { AvailableWorkUnits.Instance.GetWorkUnits( IRAPUser.Instance.CommunityID, IRAPUser.Instance.SysLogID, process.T120LeafID); lstWorkUnits.DataSource = AvailableWorkUnits.Instance.WorkUnits; lstWorkUnits.DisplayMember = "WorkUnitName"; lstWorkUnits.SelectedIndex = AvailableWorkUnits.Instance.IndexOf( CurrentOptions.Instance.WorkUnit); } catch (Exception error) { XtraMessageBox.Show( error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Refresh(); } } } private void btnSelect_Click(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); #if 歌乐 #region 根据当前选择的产品和工序,确定当前登录操作员能否操作(根据技能矩阵进行判断) WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; IRAPMESClient.Instance.usp_PokaYoke_OperatorSkill( IRAPUser.Instance.CommunityID, ((ProcessInfo)lstProcesses.SelectedItem).T102LeafID, ((WorkUnitInfo)lstWorkUnits.SelectedItem).WorkUnitLeaf, 1, IRAPUser.Instance.SysLogID, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { XtraMessageBox.Show( errText, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); XtraMessageBox.Show( string.Format( "在校验操作工技能时,发生异常:{0}", error.Message), Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } #endregion #endif CurrentOptions.Instance.Process = (ProcessInfo)lstProcesses.SelectedItem; try { CurrentOptions.Instance.WorkUnit = (WorkUnitInfo)lstWorkUnits.SelectedItem; } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); XtraMessageBox.Show( error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void frmSelectOptions_Paint(object sender, PaintEventArgs e) { btnSelect.Enabled = (lstProcesses.SelectedItem != null) && (lstWorkUnits.SelectedItem != null); } private void lstWorkUnits_Click(object sender, EventArgs e) { Refresh(); } private void lstWorkUnits_DoubleClick(object sender, EventArgs e) { Refresh(); if (btnSelect.Enabled) btnSelect.PerformClick(); } private void btnShowAll_Click(object sender, EventArgs e) { lstProcesses.DataSource = AvailableProcesses.Instance.Processes; lstProcesses.DisplayMember = "T120NodeName"; lstProcesses.SelectedIndex = AvailableProcesses.Instance.IndexOf( CurrentOptions.Instance.Process); } private void btnSearch_Click(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { lstProcesses.Items.Clear(); lstWorkUnits.DataSource = null; lstWorkUnits.Items.Clear(); int errCode = 0; string errText = ""; List<ProcessInfo> processes = new List<ProcessInfo>(); List<ProductProcessInfo> datas = new List<ProductProcessInfo>(); IRAPKBClient.Instance.ufn_GetList_GoToProduct( IRAPUser.Instance.CommunityID, edtSearchCondition.Text.Trim(), ref datas, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { XtraMessageBox.Show(errText, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { foreach (ProductProcessInfo data in datas) { foreach (ProcessInfo process in AvailableProcesses.Instance.Processes) { if (process.T102LeafID == data.T102LeafID && process.T120LeafID == data.T120LeafID) { processes.Add(process); break; } } } lstProcesses.DataSource = processes; lstProcesses.DisplayMember = "T120NodeName"; if (processes.Count > 0) lstProcesses.SelectedIndex = 0; } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); XtraMessageBox.Show( error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void edtSearchCondition_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return) btnSearch.PerformClick(); } } }
using System; using System.Collections.Generic; using System.Linq; using ContentPatcher.Framework.Conditions; using ContentPatcher.Framework.Constants; using Pathoschild.Stardew.Common.Utilities; using StardewValley; namespace ContentPatcher.Framework.Tokens.ValueProviders { /// <summary>A value provider for the player's skill levels.</summary> internal class SkillLevelValueProvider : BaseValueProvider { /********* ** Fields *********/ /// <summary>Get whether the player data is available in the current context.</summary> private readonly Func<bool> IsPlayerDataAvailable; /// <summary>The player's current skill levels.</summary> private readonly IDictionary<Skill, int> SkillLevels = new Dictionary<Skill, int>(); /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> public SkillLevelValueProvider(Func<bool> isPlayerDataAvailable) : base(ConditionType.SkillLevel, canHaveMultipleValuesForRoot: true) { this.IsPlayerDataAvailable = isPlayerDataAvailable; this.EnableInputArguments(required: false, canHaveMultipleValues: false); } /// <summary>Update the instance when the context changes.</summary> /// <param name="context">Provides access to contextual tokens.</param> /// <returns>Returns whether the instance changed.</returns> public override bool UpdateContext(IContext context) { return this.IsChanged(() => { IDictionary<Skill, int> oldSkillLevels = new Dictionary<Skill, int>(this.SkillLevels); this.SkillLevels.Clear(); this.IsReady = this.IsPlayerDataAvailable(); if (this.IsReady) { this.SkillLevels[Skill.Combat] = Game1.player.CombatLevel; this.SkillLevels[Skill.Farming] = Game1.player.FarmingLevel; this.SkillLevels[Skill.Fishing] = Game1.player.FishingLevel; this.SkillLevels[Skill.Foraging] = Game1.player.ForagingLevel; this.SkillLevels[Skill.Luck] = Game1.player.LuckLevel; this.SkillLevels[Skill.Mining] = Game1.player.MiningLevel; return this.SkillLevels.Count != oldSkillLevels.Count || this.SkillLevels.Any(entry => !oldSkillLevels.TryGetValue(entry.Key, out int oldLevel) || entry.Value != oldLevel); } return false; }); } /// <summary>Get the set of valid input arguments if restricted, or an empty collection if unrestricted.</summary> public override InvariantHashSet GetValidInputs() { return new InvariantHashSet(Enum.GetNames(typeof(Skill))); } /// <summary>Get the current values.</summary> /// <param name="input">The input argument, if applicable.</param> /// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception> public override IEnumerable<string> GetValues(string input) { this.AssertInputArgument(input); if (input != null) { if (this.TryParseEnum(input, out Skill skill) && this.SkillLevels.TryGetValue(skill, out int level)) yield return level.ToString(); } else { foreach (var pair in this.SkillLevels) yield return $"{pair.Key}:{pair.Value}"; } } } }
using CapaDatos; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Tulpep.NotificationWindow; namespace CapaUsuario.Compras.Nota_credito { public partial class FrmNotaCreditoCompras : Form { DNotaCredito dNotaCredito; DPedidoDev dPedido; private bool nueva; public FrmNotaCreditoCompras() { InitializeComponent(); } private void FrmNotaCreditoCompras_Load(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; SelectNotasCredito(); SelectPedidosDev(); } private void SelectPedidosDev() { dPedido = new DPedidoDev(); DgvPedidos.DataSource = dPedido.SelectPedidosDevSinNotaCredito(); DgvPedidos.Refresh(); } private void SelectNotasCredito() { dNotaCredito = new DNotaCredito(); DgvNotas.DataSource = dNotaCredito.SelectNotasCredito(); DgvNotas.Refresh(); } private void FrmNotaCreditoCompras_SizeChanged(object sender, EventArgs e) { DgvNotas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; DgvPedidos.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } private void CodNotaBusquedaTextBox_TextChanged(object sender, EventArgs e) { if (CodNotaBusquedaTextBox.Text.Trim() != string.Empty) { if (!int.TryParse(CodNotaBusquedaTextBox.Text.Trim(), out int codigo)) { MessageBox.Show("Ingrese solo códigos numéricos", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); CodNotaBusquedaTextBox.Text = string.Empty; return; } DgvNotas.DataSource = dNotaCredito.SelectNotasCreditoByCodNotaAndSumado( int.Parse(CodNotaBusquedaTextBox.Text.Trim()), SumadoCheckBox.Checked); DgvNotas.Refresh(); } else { SelectNotasCredito(); } } private void CrearNotaButton_Click(object sender, EventArgs e) { if (IsGridEmpty(DgvPedidos, "pedidos", "")) { return; } nueva = true; materialTabControl1.SelectedTab = TabNueva; HabilitarControles(); } private void HabilitarControles() { ImporteTextBox.ReadOnly = false; DetalleTextBox.ReadOnly = false; CancelarNuevoButton.Enabled = true; GuardarDatosButton.Enabled = true; CrearNotaButton.Enabled = false; BorrarNotaButton.Enabled = false; ModificarNotaButton.Enabled = false; CodNotaBusquedaTextBox.Enabled = false; SumadoCheckBox.Enabled = false; SumadoCheckBox.Checked = false; ImporteTextBox.Focus(); } private void DeshabilitarControles() { ImporteTextBox.ReadOnly = true; DetalleTextBox.ReadOnly = true; CancelarNuevoButton.Enabled = false; GuardarDatosButton.Enabled = false; CrearNotaButton.Enabled = true; BorrarNotaButton.Enabled = true; ModificarNotaButton.Enabled = true; CodNotaBusquedaTextBox.Enabled = true; SumadoCheckBox.Enabled = true; SumadoCheckBox.Checked = false; } private void CancelarNuevoButton_Click(object sender, EventArgs e) { DeshabilitarControles(); LimpiarCampos(); errorProvider1.Clear(); } private void LimpiarCampos() { ImporteTextBox.Text = string.Empty; DetalleTextBox.Text = string.Empty; } private void ModificarNotaButton_Click(object sender, EventArgs e) { if (IsGridEmpty(DgvNotas, "notas", "modificar")) { return; } nueva = false; var cod_nc = (int)DgvNotas.SelectedRows[0].Cells[0].Value; var dt = dNotaCredito.GetImporteAndDetalleNotaByCodNota(cod_nc); ImporteTextBox.Text = dt.Rows[0]["Importe"].ToString(); DetalleTextBox.Text = dt.Rows[0]["Detalle"].ToString(); materialTabControl1.SelectedTab = TabNueva; } private bool IsGridEmpty(DataGridView dgv, string entidad, string operacion) { if (dgv.RowCount == 0) { MessageBox.Show(operacion == "" ? $"No hay {entidad}" : $"No hay {entidad} a {operacion}", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error); return true; } return false; } private void BorrarNotaButton_Click(object sender, EventArgs e) { if (IsGridEmpty(DgvNotas, "notas", "borrar")) return; var cod_nc = (int)DgvNotas.SelectedRows[0].Cells[0].Value; try { dNotaCredito.DeleteNotaCredito(cod_nc); var popup1 = new PopupNotifier() { Image = Properties.Resources.info100, TitleText = "Mensaje", ContentText = "Se eliminó la nota de crédito con éxito", ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), ImagePadding = new Padding(0) }; popup1.Popup(); } catch (Exception ex) { ErrorMsg(ex); return; } } private static void ErrorMsg(Exception ex) { MessageBox.Show($"Error: {ex.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } private void GuardarDatosButton_Click(object sender, EventArgs e) { if (!ValidarCampos()) return; var codPedido = (int)DgvPedidos.SelectedRows[0].Cells[0].Value; var detalle = DetalleTextBox.Text.Trim(); var importe = int.Parse(DetalleTextBox.Text); if (nueva) { try { dNotaCredito.InsertNotaCredito( codPedido, false, detalle, importe); var popup1 = new PopupNotifier() { Image = Properties.Resources.sql_success1, TitleText = "Mensaje", ContentText = "Se ingresó la nota de crédito con éxito", ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), ImagePadding = new Padding(10) }; popup1.Popup(); } catch (Exception ex) { ErrorMsg(ex); return; } } else { var codNota = (int)DgvNotas.SelectedRows[0].Cells[0].Value; try { dNotaCredito.UpdateNotaCredito(codNota, detalle, importe); var popup1 = new PopupNotifier() { Image = Properties.Resources.info100, TitleText = "Mensaje", ContentText = "Se actualizó la nota de crédito con éxito", ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), ImagePadding = new Padding(0) }; popup1.Popup(); } catch (Exception ex) { ErrorMsg(ex); return; } } LimpiarCampos(); DeshabilitarControles(); SelectPedidosDev(); SelectNotasCredito(); } private bool ValidarCampos() { if (ImporteTextBox.Text.Trim() == string.Empty) { errorProvider1.SetError(ImporteTextBox, "Ingrese un importe"); ImporteTextBox.Focus(); return false; } errorProvider1.Clear(); if (ImporteTextBox.Text.Trim() != string.Empty) { if (!decimal.TryParse(ImporteTextBox.Text.Trim(), out decimal imp)) { errorProvider1.SetError(ImporteLabel, "Ingrese un valor numérico"); ImporteTextBox.Focus(); return false; } } errorProvider1.Clear(); return true; } } }
using System; namespace Oop._8_Null { class Program { static void ClaimWarranty(SoldArticle article, bool inGoodCondition, bool isBroken) { //#Bad code, highlighting the probelem //var now = DateTime.Now; //if (inGoodCondition && !isBroken && // article.MoneyBackGuatrantee != null && // article.MoneyBackGuatrantee.IsValidOn(now)) //{ // Console.WriteLine("Offer money back."); //} //if (isBroken && article.ExpressWarranty != null && // article.ExpressWarranty.IsValidOn(now)) //{ // Console.WriteLine("Offer repair"); //} } } }
using UnityEngine; using System.Collections; public class AndroidScreenHider : MonoBehaviour { float startTime = -1; void Awake() { if (Application.platform != RuntimePlatform.Android) { gameObject.SetActive(false); } } // Use this for initialization void Start () { startTime = Time.time; } // Update is called once per frame void Update () { if (Time.time - startTime > 0.1) { gameObject.SetActive (false); } } }
using System.Collections.Generic; using Configy.Containers; using Leprechaun.Model; namespace Leprechaun { public interface IOrchestrator { IReadOnlyList<ConfigurationCodeGenerationMetadata> GenerateMetadata(params IContainer[] configurations); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Globalization; namespace Stack { class Stack_Array<T> : IStack<T> { private T[] st; private int amount = 0; public Stack_Array() { st = new T[0]; } public Stack_Array(int size) { st = new T[size]; } public bool Empty() { if (amount == 0) return true; return false; } public void Push(T val) { if (amount == st.Length) throw new Exception("Переполнение стека."); st[amount++] = val; } public bool Pop() { if (Empty()) return false; amount--; return true; } public T Top() { if (amount == 0) throw new Exception("Невозможно получить первый элемент стека. Стек пуст."); return st[amount - 1]; } public int Size() { return amount; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using com.Sconit.Utility; namespace com.Sconit.Service.SI.SAP { public interface IMaterialManagementMgr { List<ErrorMessage> ExportMMMES0001Data(); List<ErrorMessage> ExportMMMES0002Data(); List<ErrorMessage> ExportSTMES0001Data(); } }
using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Text; using System.Threading.Tasks; using P1.Data.Repositories; namespace P1.Data.UnitOfWork { public class UnitOfWork : IUnitOfWork { private readonly DBModelContainer _context; public UnitOfWork() { _context = new DBModelContainer(); Media = new MediaRepository(_context); Tags = new TagsRepository(_context); } public IMediaRepository Media { get; private set; } public ITagsRepository Tags { get; private set; } public Media RemoveTagFromMedia(Media media, int tagId) { if (media == null) return media; Tags tag = Tags.Get(tagId); media.Tags.Remove(tag); Tags.Delete(tag.Id); Complete(); return media; } public Media AddTagToMedia(Media media, Tags tag) { if (media == null) return media; media.Tags.Add(tag); Complete(); return media; } public int Complete() { try { return _context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } } public void Dispose() { _context.Dispose(); } } }
using EmberKernel.Services.Statistic; using System; namespace EmberKernel { public static class StatisticKernelBuilderExtension { public static KernelBuilder UseStatistic(this KernelBuilder builder, Action<StatisticBuilder> build) { var statisticBuilder = new StatisticBuilder(builder); build(statisticBuilder); return builder; } } }
using System; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Windows.Forms; namespace InstaladorMapsCS { public partial class frm2Instalacao : Form { private frm1Inicial form1; public frm2Instalacao(frm1Inicial form) { InitializeComponent(); this.form1 = form; label1.Text = "Diretorio selecionado:\n" + form1.txtPath.Text; string[] mapsNames = EmbeddedResources.getNameItemsFromPath("cstrike.maps").Select(c => c.Replace(".bsp", "")).ToArray(); listarNaLabel(mapsNames, label2, 2); } private void btnVoltar_Click(object sender, EventArgs e) { form1.Show(); this.Close(); } private void frm2Instalacao_FormClosing(object sender, FormClosingEventArgs e) { if (!form1.Visible) { Environment.Exit(0); } } private void btnInstalar_Click(object sender, EventArgs e) { bool sucessInstall = false; if (btnInstalar.Text == "Fechar") { Environment.Exit(0); return; } btnInstalar.Enabled = false; BackgroundWorker workerLeituraArquivos = new BackgroundWorker(); workerLeituraArquivos.WorkerReportsProgress = true; workerLeituraArquivos.DoWork += (sender1, e1) => { try { string[] items = EmbeddedResources.getResourceLocationFiles("cstrike"); for (int i = 0; i < items.Length; i++) { //remove o nome do projeto e retorna pastas e subpastas em diretorios string pathDir = EmbeddedResources.transformStringPathEmbeddedResourcesInDirectories(items[i]); //concateno o destino com todas as pastas filho incluindo o item na (newpath) EmbeddedResources.ExtractEmbeddedResource(form1.txtPath.Text.Replace(@"\cstrike", "") + @"\" + pathDir, items[i]); int porcentagem = (i + 1) * 100 / items.Length; workerLeituraArquivos.ReportProgress(porcentagem); } sucessInstall = true; } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } }; workerLeituraArquivos.ProgressChanged += (sender1, e1) => { lblStatus.Text = string.Format("Copiando arquivos. {0}% concluído", e1.ProgressPercentage); progressBar1.Value = e1.ProgressPercentage; }; workerLeituraArquivos.RunWorkerCompleted += (sender1, e1) => { if (sucessInstall) { lblStatus.Text = "Instalação Finalizada."; btnInstalar.Enabled = true; btnInstalar.Text = "Fechar"; btnVoltar.Visible = false; } }; workerLeituraArquivos.RunWorkerAsync(); } private void listarNaLabel(string[] lista, Label label, int espacamento) { //ordena a lista pelo tamanho das palavras e alfabeto lista = lista.OrderBy(x => x.Length).ThenBy(x => x).ToArray(); //quantidade de linhas que cabe ate o final da label (cima para baixo) int qnt_line = label.Height / label.Font.Height; int qnt_colunas_necessario = lista.Length / qnt_line;// (int)Math.Ceiling(lista.Length / (double)qnt_line); int qnt_sobra = lista.Length % qnt_line; int[] maiorPalavraCadaColuna = new int[qnt_colunas_necessario]; //int[] maiorPalavraCadaColuna = new int[qnt_colunas_necessario + (qnt_sobra > 0 ? 1 : 0)]; int temp = 0; for (int i = 0; i < qnt_colunas_necessario; i++) { maiorPalavraCadaColuna[i] = 0; //caça a maior palavra de cada coluna for (int j = temp; j < qnt_line * (i + 1); j++) if (maiorPalavraCadaColuna[i] < lista[j].Length) maiorPalavraCadaColuna[i] = lista[j].Length; //adiciona espaçamento em todas palavras conforme o tamanho da maior palavra for (int j = temp; j < qnt_line * (i + 1); j++) lista[j] = lista[j].PadRight(maiorPalavraCadaColuna[i] + espacamento); temp = qnt_line * (i + 1); } ////maior palavra da coluna de sobra. *133 //for (int i = temp; i < temp + qnt_sobra; i++) // if (maiorPalavraCadaColuna[maiorPalavraCadaColuna.Length - 1] < lista[i].Length) // maiorPalavraCadaColuna[maiorPalavraCadaColuna.Length - 1] = lista[i].Length; //formata a string cabendo os array string listaFormatada = ""; if (qnt_colunas_necessario > 1) { for (int i = 0; i < qnt_line; i++) { for (int j = 0; j < qnt_colunas_necessario; j++) listaFormatada += lista[i + qnt_line * j]; if (qnt_sobra > 0) listaFormatada += lista[lista.Length - qnt_sobra--]; listaFormatada += "\n"; } } else { if (lista.Length < qnt_line) { foreach (string item in lista) { listaFormatada += item + "\n"; } } } label.Text = listaFormatada; /* Label Caracteres Width 8 9 10 11 14 ------------------------- 1 13 14 14 16 20 2 19 21 21 24 30 3 25 28 28 40 4 31 35 35 50 borders = 7 caracter = 6 // */ } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { MessageBox.Show(null, "installer created by: caio s.", "thanks."); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Raycast to get collision with enemies and change the list of enemies can be attack /// </summary> public class MeeleAttack : MonoBehaviour { public RaycastHit2D hitDown, hitUp, hitLeft, hitRight; private EnemyController lastEnemyDown, lastEnemyUp, lastEnemyLeft, lastEnemyRight; private PlayerController _playerMeeleController; public LayerMask enemieLayerMask; public float distanceToAttack; public bool drawnLines; void Awake() { _playerMeeleController = GetComponentInParent<PlayerController>(); } void Update() { hitDown = Physics2D.Raycast(transform.position, Vector2.down, distanceToAttack, enemieLayerMask); hitUp = Physics2D.Raycast(transform.position, Vector2.up, distanceToAttack, enemieLayerMask); hitRight = Physics2D.Raycast(transform.position, Vector2.right, distanceToAttack, enemieLayerMask); hitLeft = Physics2D.Raycast(transform.position, Vector2.left, distanceToAttack, enemieLayerMask); // For each RaycastHit2D that collide with the enemy we change the list of the enemies of player can attack if (hitDown.collider != null) { lastEnemyDown = hitDown.collider.gameObject.GetComponent<EnemyController>(); lastEnemyDown.SetState(EnemyController.EnemyState.EnableToAttack); ChangeListEnemiesPlayer(lastEnemyDown, true); } else { if (lastEnemyDown != null) { lastEnemyDown.SetState(EnemyController.EnemyState.Ready); ChangeListEnemiesPlayer(lastEnemyDown, false); lastEnemyDown = null; } } if (hitUp.collider != null) { lastEnemyUp = hitUp.collider.gameObject.GetComponent<EnemyController>(); lastEnemyUp.SetState(EnemyController.EnemyState.EnableToAttack); ChangeListEnemiesPlayer(lastEnemyUp, true); } else { if (lastEnemyUp != null) { lastEnemyUp.SetState(EnemyController.EnemyState.Ready); ChangeListEnemiesPlayer(lastEnemyUp, false); lastEnemyUp = null; } } if (hitRight.collider != null) { lastEnemyRight = hitRight.collider.gameObject.GetComponent<EnemyController>(); lastEnemyRight.SetState(EnemyController.EnemyState.EnableToAttack); ChangeListEnemiesPlayer(lastEnemyRight, true); } else { if (lastEnemyRight != null) { lastEnemyRight.SetState(EnemyController.EnemyState.Ready); ChangeListEnemiesPlayer(lastEnemyRight, false); lastEnemyRight = null; } } if (hitLeft.collider != null) { lastEnemyLeft = hitLeft.collider.gameObject.GetComponent<EnemyController>(); lastEnemyLeft.SetState(EnemyController.EnemyState.EnableToAttack); ChangeListEnemiesPlayer(lastEnemyLeft, true); } else { if (lastEnemyLeft != null) { lastEnemyLeft.SetState(EnemyController.EnemyState.Ready); ChangeListEnemiesPlayer(lastEnemyLeft, false); lastEnemyLeft = null; } } } private void ChangeListEnemiesPlayer(EnemyController enemyController, bool add) { if (add) { if(!_playerMeeleController.enemiesToAttack.Contains(enemyController)) _playerMeeleController.enemiesToAttack.Add(enemyController); } else { if (_playerMeeleController.enemiesToAttack.Contains(enemyController)) _playerMeeleController.enemiesToAttack.Remove(enemyController); } } private void OnDrawGizmos() { Gizmos.color = Color.magenta; if (drawnLines) { Gizmos.DrawLine(transform.position, new Vector2(transform.position.x, transform.position.y - distanceToAttack)); Gizmos.DrawLine(transform.position, new Vector2(transform.position.x, transform.position.y + distanceToAttack)); Gizmos.DrawLine(transform.position, new Vector2(transform.position.x - distanceToAttack, transform.position.y)); Gizmos.DrawLine(transform.position, new Vector2(transform.position.x + distanceToAttack, transform.position.y)); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using TestHouse.Application.Infastructure.Repositories; using TestHouse.Application.Extensions; using TestHouse.Domain.Models; using TestHouse.Domain.Enums; using TestHouse.DTOs.DTOs; namespace TestHouse.Application.Services { public class ProjectService { private readonly IProjectRepository _projectRepository; public ProjectService(IProjectRepository projectRepository) { _projectRepository = projectRepository; } /// <summary> /// Add new project /// </summary> /// <param name="name">Name of the project</param> /// <param name="description">Description of the project</param> /// <returns>Created project dto</returns> public async Task<ProjectDto> AddProjectAsync(string name, string description) { var project = new ProjectAggregate(name, description); _projectRepository.Add(project); await _projectRepository.SaveAsync(); return project.ToProjectDto(); } /// <summary> /// Get all existing projects /// </summary> /// <returns>List of projects dto</returns> public async Task<IEnumerable<ProjectDto>> GetAllAsync() { var projectAggregates = await _projectRepository.GetAllAsync(); return projectAggregates.ToProjectsDto(); } /// <summary> /// Get project aggregate /// </summary> /// <param name="id">Project id</param> /// <returns></returns> public async Task<ProjectAggregateDto> GetAsync(long id) { var project = await _projectRepository.GetAsync(id); return project?.ToProjectAggregateDto(); } /// <summary> /// Update project info /// </summary> /// <param name="id">Project id</param> /// <param name="name">Project name</param> /// <param name="description">Project description</param> /// <returns></returns> public async Task UpdateProject(long id, string name, string description) { var project = await _projectRepository.GetAsync(id); project.UpdateInfo(name, description); await _projectRepository.SaveAsync(); } /// <summary> /// Remove project aggregate /// </summary> /// <param name="id">Project id</param> /// <returns></returns> public async Task RemoveAsync(long id) { var project = await _projectRepository.GetAsync(id); project.UpdateState(ProjectAggregateState.Deleted); await _projectRepository.SaveAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DSG东莞路测客户端 { class WhiteRadioInfo { public int ID { get; set; } public string DateTime { get; set; } public double Freq { get; set; }//MHz public double Width { get; set; }//KHz public string RadioName { get; set; }//电台名称 public string Mark { get; set; }//备注 public string RecordUsr { get; set; } public string Province { get; set; } public string City { get; set; } public string District { get; set; } private static List<WhiteRadioInfo> mlist = new List<WhiteRadioInfo>(); public static async void GetWhiteRadioListFromServer() { NormalResponse np = await API.GetWhiteRadio(); if (!np.result) { return; } else { mlist = np.Parse<List<WhiteRadioInfo>>(); if (mlist != null && mlist.Count > 0) { foreach (var itm in mlist) { itm.Freq = Math.Round(itm.Freq, 1); } } } } public static WhiteRadioInfo GetSignalInfo(double freq) { if (mlist == null || mlist.Count == 0) return null; freq = Math.Round(freq, 1); return mlist.Where(a => a.Freq == freq).FirstOrDefault(); } } }
namespace Drivers.Led { public enum Intensity { Highest = 0, High = 1, MediumHigh = 2, Medium = 3, MediumLow = 4, Low = 5, Lowest = 6, Off = 7 } }
using DAL.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class RepositoryContext : DbContext { public RepositoryContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Product>() .Property(p => p.Price) .HasColumnType("decimal(18, 2)"); modelBuilder.Entity<Product>(b => { b.HasKey(k => k.ProductId); b.Property(k => k.ProductId).ValueGeneratedOnAdd(); }); modelBuilder.Entity<Category>() .HasMany(c => c.Products) .WithOne(c => c.Category); } /*.HasMany(c => c.Employees) .WithOne(e => e.Company);*/ public DbSet<Product> Products { get; set; } public DbSet<Category> Categories { get; set; } } }
using System.Web.Mvc; using CAPCO.Infrastructure.Domain; using CAPCO.Infrastructure.Data; namespace CAPCO.Areas.Admin.Controllers { public class DiscountCodesController : BaseAdminController { private readonly IRepository<DiscountCode> discountcodeRepository; public DiscountCodesController(IRepository<DiscountCode> discountcodeRepository) { this.discountcodeRepository = discountcodeRepository; } public ViewResult Index() { return View(discountcodeRepository.All); } public ActionResult New() { return View(); } [HttpPost, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Create(DiscountCode discountcode) { if (ModelState.IsValid) { discountcodeRepository.InsertOrUpdate(discountcode); discountcodeRepository.Save(); this.FlashInfo("The discount code was successfully created."); return RedirectToAction("Index"); } this.FlashError("There was a problem creating the discount code."); return View("New", discountcode); } public ActionResult Edit(int id) { return View(discountcodeRepository.Find(id)); } [HttpPut, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Update(int id, DiscountCode discountcode) { if (ModelState.IsValid) { var toUpdate = discountcodeRepository.Find(id); if (toUpdate == null) { this.FlashError("There is no discount code with that id."); return RedirectToAction("index"); } toUpdate.Code = discountcode.Code; toUpdate.Name = discountcode.Name; discountcodeRepository.InsertOrUpdate(toUpdate); discountcodeRepository.Save(); this.FlashInfo("The was successfully saved."); return RedirectToAction("Index"); } this.FlashError("There was a problem saving the discount code."); return View("Edit", discountcode); } public ActionResult Delete(int id) { discountcodeRepository.Delete(id); discountcodeRepository.Save(); this.FlashInfo("The discount code was successfully deleted."); return RedirectToAction("Index"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Utils { static System.Random rnd = new System.Random(); static public void ShuffleAndPlaceOnTop<T>(List<T> toShuffle, Stack<T> existingDeck){ for (int n = toShuffle.Count - 1; n >= 0; n--) { int k = rnd.Next(n + 1); existingDeck.Push(toShuffle[k]); toShuffle.RemoveAt(k); } } }
namespace Fingo.Auth.ManagementApp.Models.Enums { public enum SortByColumn { Name , EventType , EventMessage , CreationDate } }
using System; using ServiceStack; using ServiceStack.DataAnnotations; using SsWkPdf.ServiceModel.Type; using WkHtmlToXSharp; namespace SsWkPdf.ServiceModel { public class WebDocuments { [Route("/webdocument", "POST", Summary = "Creates the document.")] public class CreateRequest : IReturn<WebDocumentMetadata> { /// <summary> /// Gets or sets the source URL. /// </summary> /// <value> /// The source URL. /// </value> public string SourceUrl { get; set; } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value> /// The name of the file. /// </value> public string FileName { get; set; } /// <summary> /// Gets or sets the type of the use print media. /// </summary> /// <value> /// The type of the use print media. /// </value> public bool? UsePrintMediaType { get; set; } /// <summary> /// Gets or sets the margin top. /// </summary> /// <value> /// The margin top. /// </value> public string MarginTop { get; set; } /// <summary> /// Gets or sets the margin bottom. /// </summary> /// <value> /// The margin bottom. /// </value> public string MarginBottom { get; set; } /// <summary> /// Gets or sets the margin left. /// </summary> /// <value> /// The margin left. /// </value> public string MarginLeft { get; set; } /// <summary> /// Gets or sets the margin right. /// </summary> /// <value> /// The margin right. /// </value> public string MarginRight { get; set; } /// <summary> /// Gets or sets the orientation. /// </summary> /// <value> /// The orientation. /// </value> public PdfOrientation? Orientation { get; set; } } [Route("/webdocument/{Id}/delete", "GET DELETE", Summary = "Deletes the document by id.")] public class DeleteRequest : FindByIdRequest { } [Route("/webdocument/{Id}/download", "GET", Summary = "Downloads a document by id.")] public class DownloadRequest : FindByIdRequest { } [Route("/webdocument/{Id}", "GET", Summary = "View a document by id.")] [Route("/webdocument/{Id}", "DELETE", Summary = "Deletes the document by id.")] public class FindByIdRequest : IReturn<WebDocumentMetadata> { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public Guid Id { get; set; } } [Route("/webdocuments", "GET", Summary = "Page through all the documents.")] [Route("/webdocuments/{Page}", "GET", Summary = "Page through all the documents.")] public class FindRequest : IReturn<PagedResponse<MetadataResponse>> { /// <summary> /// Gets or sets the page. /// </summary> /// <value> /// The page. /// </value> public int Page { get; set; } /// <summary> /// Gets or sets the size of the page. /// </summary> /// <value> /// The size of the page. /// </value> public int PageSize { get; set; } /// <summary> /// Gets or sets from. /// </summary> /// <value> /// From. /// </value> public DateTimeOffset? From { get; set; } /// <summary> /// Gets or sets to. /// </summary> /// <value> /// To. /// </value> public DateTimeOffset? To { get; set; } } [Route("/webdocument/{Id}/metadata", "GET", Summary = "View the document metadata by id.")] public class MetadataRequest : FindByIdRequest, IReturn<MetadataResponse> { } public class MetadataResponse : WebDocumentMetadata, IHasResponseStatus { /// <summary> /// Gets or sets the response status. /// </summary> /// <value> /// The response status. /// </value> public ResponseStatus ResponseStatus { get; set; } } [Route("/webdocument", "POST", Summary = "Updates the document.")] [Route("/webdocument/{Id}", "POST PUT", Summary = "Updates the document.")] public class UpdateRequest : CreateRequest { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public Guid Id { get; set; } /// <summary> /// Gets or sets the record version. /// </summary> /// <value> /// The record version. /// </value> [Description("Record Version when first retrieved, for concurrency checking.")] public int RecordVersion { get; set; } } } }
namespace InoDrive.Domain.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Bids", c => new { BidId = c.Int(nullable: false, identity: true), IsAccepted = c.Boolean(), IsWatchedBySender = c.Boolean(nullable: false), IsWatchedByReceiver = c.Boolean(nullable: false), CreationDate = c.DateTimeOffset(nullable: false, precision: 7), UserId = c.String(maxLength: 128), TripId = c.Int(nullable: false), }) .PrimaryKey(t => t.BidId) .ForeignKey("dbo.Trips", t => t.TripId) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId) .Index(t => t.TripId); CreateTable( "dbo.Trips", c => new { TripId = c.Int(nullable: false, identity: true), UserId = c.String(maxLength: 128), CreationDate = c.DateTimeOffset(nullable: false, precision: 7), LeavingDate = c.DateTimeOffset(nullable: false, precision: 7), EndDate = c.DateTimeOffset(nullable: false, precision: 7), PeopleCount = c.Int(nullable: false), IsAllowdedDeviation = c.Boolean(nullable: false), IsAllowdedChildren = c.Boolean(nullable: false), IsAllowdedPets = c.Boolean(nullable: false), IsAllowdedMusic = c.Boolean(nullable: false), IsAllowdedEat = c.Boolean(nullable: false), IsAllowdedDrink = c.Boolean(nullable: false), IsAllowdedSmoke = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), About = c.String(), Car = c.String(), CarImage = c.String(), CarImageExtension = c.String(), CarClass = c.String(), OriginPlaceId = c.String(nullable: false, maxLength: 128), DestinationPlaceId = c.String(nullable: false, maxLength: 128), Pay = c.Decimal(storeType: "money"), }) .PrimaryKey(t => t.TripId) .ForeignKey("dbo.Places", t => t.DestinationPlaceId) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .ForeignKey("dbo.Places", t => t.OriginPlaceId) .Index(t => t.UserId) .Index(t => t.OriginPlaceId) .Index(t => t.DestinationPlaceId); CreateTable( "dbo.Places", c => new { PlaceId = c.String(nullable: false, maxLength: 128), Name = c.String(), About = c.String(), Latitude = c.Double(nullable: false), Longitude = c.Double(nullable: false), }) .PrimaryKey(t => t.PlaceId); CreateTable( "dbo.Likes", c => new { LikeId = c.Int(nullable: false, identity: true), Vote = c.Int(nullable: false), UserId = c.String(maxLength: 128), TripId = c.Int(nullable: false), }) .PrimaryKey(t => t.LikeId) .ForeignKey("dbo.Trips", t => t.TripId) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId) .Index(t => t.TripId); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), FirstName = c.String(), LastName = c.String(), DateOfBirth = c.DateTimeOffset(precision: 7), DateOfStage = c.DateTimeOffset(precision: 7), Phone = c.String(), About = c.String(), AvatarImage = c.String(), AvatarImageExtension = c.String(), Car = c.String(), CarImage = c.String(), CarImageExtension = c.String(), CarClass = c.String(), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .ForeignKey("dbo.AspNetRoles", t => t.RoleId) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.WayPoints", c => new { WayPointId = c.Int(nullable: false, identity: true), WayPointIndex = c.Int(nullable: false), TripId = c.Int(nullable: false), PlaceId = c.String(maxLength: 128), }) .PrimaryKey(t => t.WayPointId) .ForeignKey("dbo.Places", t => t.PlaceId) .ForeignKey("dbo.Trips", t => t.TripId) .Index(t => t.TripId) .Index(t => t.PlaceId); CreateTable( "dbo.Clients", c => new { Id = c.String(nullable: false, maxLength: 128), Secret = c.String(nullable: false), Name = c.String(nullable: false, maxLength: 100), ApplicationType = c.Int(nullable: false), Active = c.Boolean(nullable: false), RefreshTokenLifeTime = c.Int(nullable: false), AllowedOrigin = c.String(maxLength: 100), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RefreshTokens", c => new { Id = c.String(nullable: false, maxLength: 128), Subject = c.String(nullable: false, maxLength: 50), ClientId = c.String(nullable: false, maxLength: 50), IssuedUtc = c.DateTime(nullable: false), ExpiresUtc = c.DateTime(nullable: false), ProtectedTicket = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.WayPoints", "TripId", "dbo.Trips"); DropForeignKey("dbo.WayPoints", "PlaceId", "dbo.Places"); DropForeignKey("dbo.Trips", "OriginPlaceId", "dbo.Places"); DropForeignKey("dbo.Trips", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Likes", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Bids", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Likes", "TripId", "dbo.Trips"); DropForeignKey("dbo.Trips", "DestinationPlaceId", "dbo.Places"); DropForeignKey("dbo.Bids", "TripId", "dbo.Trips"); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.WayPoints", new[] { "PlaceId" }); DropIndex("dbo.WayPoints", new[] { "TripId" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.Likes", new[] { "TripId" }); DropIndex("dbo.Likes", new[] { "UserId" }); DropIndex("dbo.Trips", new[] { "DestinationPlaceId" }); DropIndex("dbo.Trips", new[] { "OriginPlaceId" }); DropIndex("dbo.Trips", new[] { "UserId" }); DropIndex("dbo.Bids", new[] { "TripId" }); DropIndex("dbo.Bids", new[] { "UserId" }); DropTable("dbo.AspNetRoles"); DropTable("dbo.RefreshTokens"); DropTable("dbo.Clients"); DropTable("dbo.WayPoints"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.Likes"); DropTable("dbo.Places"); DropTable("dbo.Trips"); DropTable("dbo.Bids"); } } }
using UnityEngine; using System.Collections; /// <summary> /// Simple killzone script that will kill player if they jump off the map /// </summary> public class Killzone : MonoBehaviour { int damage; GameObject player; PlayerHP playerHP; // Use this for initialization void Start () { damage = 1000; //set high to instantly kill player player = GameObject.Find("Player"); playerHP = player.GetComponent<PlayerHP>(); } // Update is called once per frame void Update () { } /// <summary> /// when the killzone and player collide it kills the player immediately /// </summary> /// <param name="col"></param> void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.tag == "Player") { playerHP.takeDamage(damage); } } }
using Domain.Entities; using Domain.InterfaceRepo; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Repositories { public class EfCapacityRepository : IRepository<Capacity> { static Context context; public EfCapacityRepository(Context dbcontext) { context = dbcontext; } public Capacity Add(Capacity item) { context.Capacities.Add(item); context.SaveChanges(); return item; } public Capacity Get(int id) { return context.Capacities.ToList().Find(c => c.ID == id); } public IEnumerable<Capacity> GetAll() { return context.Capacities; } public Capacity Remove(int id) { Capacity item = Get(id); context.Capacities.Remove(item); context.SaveChanges(); return item; } public bool Update(Capacity item) { int index = context.Capacities.ToList().FindIndex(c => c.ID == item.ID); if (index == -1) return false; context.Capacities.ToList().RemoveAt(index); context.Capacities.Add(item); context.SaveChanges(); return true; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form3 : Form { public Form3() { InitializeComponent(); } private void Form3_Load(object sender, EventArgs e) { this.MaximizeBox = false; this.MinimizeBox = false; this.button1.Font = new Font("Times New Roman", 20); this.BackgroundImage = new Bitmap(@"C:\Users\H.S\Downloads\gameover.png"); this.button1.Text = "OK"; } private void button1_Click(object sender, EventArgs e) { Form1 f1 = new Form1(); f1.Show(); Close(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Problem_01 { class Program { static void Main() { var users = new Dictionary<string, Dictionary<string, int>>(); var individualStatistics = new Dictionary<string, int>(); string command = Console.ReadLine(); while (command != "no more time") { string[] line = command.Split(" -> "); string username = line[0]; string contest = line[1]; int points = int.Parse(line[2]); bool itMustSum = false; if (!(username.Contains(" ") || contest.Contains(" "))) { if (users.ContainsKey(contest)) { if (users[contest].ContainsKey(username)) { int currentPoints = users[contest][username]; if (currentPoints < points) { users[contest][username] = points; points -= currentPoints; itMustSum = true; } } else { users[contest].Add(username, points); itMustSum = true; } } else { users.Add(contest, new Dictionary<string, int>()); users[contest].Add(username, points); itMustSum = true; } if (!individualStatistics.ContainsKey(username)) { individualStatistics[username] = 0; } if (itMustSum) { individualStatistics[username] += points; } } command = Console.ReadLine(); } foreach (var contest in users) { Console.WriteLine($"{contest.Key}: {contest.Value.Keys.Count} participants"); int position = 1; foreach (var user in contest.Value.OrderByDescending(x => x.Value).ThenBy(x => x.Key)) { Console.WriteLine($"{position++}. {user.Key} <::> {user.Value}"); } } Console.WriteLine("Individual standings:"); int positions = 1; foreach (var statistics in individualStatistics.OrderByDescending(x => x.Value).ThenBy(x => x.Key)) { Console.WriteLine($"{positions++}. {statistics.Key} -> {statistics.Value}"); } } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class MusicButton : MonoBehaviour { bool registeredForEvents; Sprite onSprite; Sprite offSprite; public Image buttonImage; void Awake() { string path; path = "Textures/Buttons/music_button.01"; onSprite = Resources.Load<UnityEngine.Sprite>(path); path = "Textures/Buttons/music_button_off.01"; offSprite = Resources.Load<UnityEngine.Sprite>(path); } // Use this for initialization void Start () { RegisterForEvents (); UpdateButtonImage (); } void OnDestroy() { UnregisterForEvents (); } void RegisterForEvents() { if (registeredForEvents) { return; } registeredForEvents = true; SoundController.instance.MusicMuteChanged += new SoundController.MusicMuteChangedEventHandler (OnMusicMuteChanged); } void UnregisterForEvents() { if (registeredForEvents) { SoundController.instance.MusicMuteChanged -= new SoundController.MusicMuteChangedEventHandler (OnMusicMuteChanged); } } void OnMusicMuteChanged() { UpdateButtonImage (); } // Update is called once per frame void UpdateButtonImage () { if (SoundController.instance.musicMuted) { buttonImage.sprite = offSprite; } else { buttonImage.sprite = onSprite; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { // convert ‘hello world’ to ‘HelloWorld’ // punctuation is turned into ‘_’, others are ignored. public static string Capitalize(string value) { // WARNING: this sample is for demonstration only: it *contains* bugs. var sb = new StringBuilder(); bool word = false; foreach (var c in value) { if (char.IsLetter(c)) { if (word) sb.Append(c); else { sb.Append(char.ToUpper(c)); word = true; } } else { if (c == '!') sb.Append('_'); word = false; } } return sb.ToString(); }// Credit goes to Peli and Nickolai http://www.codeproject.com/Articles/31141/Getting-started-with-automated-white-box-testing-a } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class RiverHandler : MonoBehaviour { public GameObject RiverPrefab; public Sprite[] RiverSprite; public Sprite RiverStart; private int[,] index = new int[,] { { 0, 1, 2, 3, 2, 1 }, { 1, 0, 1, 2, 3, 2 }, { 2, 1, 0, 1, 2, 3 }, { 3, 2, 1, 0, 1, 2 }, { 2, 3, 2, 1, 0, 1 }, { 1, 2, 3, 2, 1, 0 } }; public void SetRiver(Region region, Color waterColor) { try { foreach (var r in region.River.pairs) { GameObject river = Instantiate(RiverPrefab, transform, false); SpriteRenderer spriteRenderer = river.GetComponent<SpriteRenderer>(); spriteRenderer.color = Color.Lerp(Color.black, waterColor, region.Altitude); spriteRenderer.sortingOrder = 2; if (r.above == -1) { spriteRenderer.sprite = RiverStart; river.transform.rotation = Quaternion.Euler(0, 0, 60 * r.below); } else { int rotate = Math.Abs(r.below - r.above) == 2 ? (r.below > r.above ? r.above : r.below) : (r.below < r.above ? r.above : r.below); river.transform.rotation = Quaternion.Euler(0, 0, 60 * rotate); spriteRenderer.sprite = RiverSprite[index[r.above, r.below]]; } } } catch (Exception) { Debug.Log(index); } } }
using System; using UnityEngine; using HoloToolkit.Unity; using HoloToolkit.Unity.InputModule; [RequireComponent(typeof(AudioSource))] public abstract class HandTransformation : MonoBehaviour, IFocusable, IInputHandler, ISourceStateHandler { public event Action StartedTransformation; public event Action StoppedTransformation; [Tooltip("Transform that will be dragged. Defaults to the object of the component.")] public Transform HostTransform; [Tooltip("Scale by which hand movement in z is multipled to move the dragged object.")] public float DistanceScale = 2.0f; [Tooltip("Should the object be oriented towards the user as it is being dragged?")] public bool IsOrientTowardsUser = false; [Tooltip("Should the object be kept upright as it is being dragged?")] public bool IsKeepUpright = true; private bool isGazed; private bool isTransforming; private uint currentInputSourceId; private IInputSource currentInputSource; private Quaternion gazeAngularOffset; private float handRefDistance; private float objRefDistance; private AudioSource audioSource; private AudioClip inputDown; protected Camera mainCamera; protected Vector3 objRefGrabPoint; protected Vector3 draggingPosition; protected Vector3 objRefForward; protected Quaternion draggingRotation; public void OnFocusEnter() { if (isGazed) return; isGazed = true; } public void OnFocusExit() { isGazed = false; } public void OnInputDown(InputEventData eventData) { audioSource.PlayOneShot(inputDown); currentInputSource = eventData.InputSource; currentInputSourceId = eventData.SourceId; StartTransform(); } public void OnInputUp(InputEventData eventData) { audioSource.PlayOneShot(inputDown); StopTransform(); } public void OnSourceDetected(SourceStateEventData eventData) { // do nothing } public void OnSourceLost(SourceStateEventData eventData) { audioSource.PlayOneShot(inputDown); StopTransform(); } private void StartTransform() { InputManager.Instance.PushModalInputHandler(gameObject); isTransforming = true; Vector3 gazeHitPosition = GazeManager.Instance.HitInfo.point; Vector3 handPosition; currentInputSource.TryGetPosition(currentInputSourceId, out handPosition); Vector3 pivotPosition = GetHandPivotPosition(); handRefDistance = Vector3.Magnitude(handPosition - pivotPosition); objRefDistance = Vector3.Magnitude(gazeHitPosition - pivotPosition); objRefGrabPoint = mainCamera.transform.InverseTransformDirection(HostTransform.position - gazeHitPosition); Vector3 objForward = HostTransform.forward; Vector3 objDirection = Vector3.Normalize(gazeHitPosition - pivotPosition); Vector3 handDirection = Vector3.Normalize(handPosition - pivotPosition); objForward = mainCamera.transform.InverseTransformDirection(objForward); objDirection = mainCamera.transform.InverseTransformDirection(objDirection); handDirection = mainCamera.transform.InverseTransformDirection(handDirection); objRefForward = objForward; gazeAngularOffset = Quaternion.FromToRotation(handDirection, objDirection); draggingPosition = gazeHitPosition; StartedTransformation.RaiseEvent(); } private void UpdateTransform() { // get the hand's current position vector Vector3 newHandPosition; currentInputSource.TryGetPosition(currentInputSourceId, out newHandPosition); // this estimates where your head is by using the camera's position Vector3 pivotPosition = GetHandPivotPosition(); // calculate the hand's direction vector relative to the head by subtracting // the above two vectors and normalizing Vector3 newHandDirection = Vector3.Normalize(newHandPosition - pivotPosition); // change that direction from world space to local camera space that way // it doesn't matter which way the head is pointed newHandDirection = mainCamera.transform.InverseTransformDirection(newHandDirection); // normalize to get just the direction Vector3 targetDirection = Vector3.Normalize(gazeAngularOffset * newHandDirection); targetDirection = mainCamera.transform.TransformDirection(targetDirection); // find the distance the hand is from the head float currenthandDistance = Vector3.Magnitude(newHandPosition - pivotPosition); // find the ratio of the current hand distance to the original distance float distanceRatio = currenthandDistance / handRefDistance; // scale the movement based on how close or far the hand is (probably adds stability) float distanceOffset = distanceRatio > 0 ? (distanceRatio - 1f) * DistanceScale : 0; // a measure of the the distance of the object from the head plus the stabilizing offset float targetDistance = objRefDistance + distanceOffset; // multiply target direction vector by target magnitude to get target position // then add to pivot position to put back in world position Vector3 newDraggingPosition = pivotPosition + (targetDirection * targetDistance); // change that direction from world space to local camera space // that way it doesn't matter which way the head is pointed Vector3 delta = mainCamera.transform.InverseTransformDirection(draggingPosition - newDraggingPosition); ApplyTransformation(pivotPosition, newDraggingPosition, delta); } protected abstract void ApplyTransformation(Vector3 pivotPosition, Vector3 newPosition, Vector3 delta); private void StopTransform() { if (!isTransforming) return; InputManager.Instance.PopModalInputHandler(); isTransforming = false; currentInputSource = null; StoppedTransformation.RaiseEvent(); } private Vector3 GetHandPivotPosition() { Vector3 pivot = Camera.main.transform.position + new Vector3(0, -0.2f, 0) - Camera.main.transform.forward * 0.2f; // a bit lower and behind return pivot; } private void Awake() { audioSource = GetComponent<AudioSource>(); audioSource.spatialBlend = 1.0f; } private void Start() { inputDown = Resources.Load<AudioClip>("Sounds/Clap Simple Snap"); if (HostTransform == null) { HostTransform = transform; } mainCamera = Camera.main; } private void Update() { if (isTransforming) UpdateTransform(); } }
using System; namespace ScriptKit { [Flags] public enum JsRuntimeAttributes { /// <summary> /// No special attributes. /// </summary> JsRuntimeAttributeNone = 0x00000000, /// <summary> /// The runtime will not do any work (such as garbage collection) on background threads. /// </summary> JsRuntimeAttributeDisableBackgroundWork = 0x00000001, /// <summary> /// The runtime should support reliable script interruption. This increases the number of /// places where the runtime will check for a script interrupt request at the cost of a /// small amount of runtime performance. /// </summary> JsRuntimeAttributeAllowScriptInterrupt = 0x00000002, /// <summary> /// Host will call <c>JsIdle</c>, so enable idle processing. Otherwise, the runtime will /// manage memory slightly more aggressively. /// </summary> JsRuntimeAttributeEnableIdleProcessing = 0x00000004, /// <summary> /// Runtime will not generate native code. /// </summary> JsRuntimeAttributeDisableNativeCodeGeneration = 0x00000008, /// <summary> /// Using <c>eval</c> or <c>function</c> constructor will throw an exception. /// </summary> JsRuntimeAttributeDisableEval = 0x00000010, /// <summary> /// Runtime will enable all experimental features. /// </summary> JsRuntimeAttributeEnableExperimentalFeatures = 0x00000020, /// <summary> /// Calling <c>JsSetException</c> will also dispatch the exception to the script debugger /// (if any) giving the debugger a chance to break on the exception. /// </summary> JsRuntimeAttributeDispatchSetExceptionsToDebugger = 0x00000040, /// <summary> /// Disable Failfast fatal error on OOM /// </summary> JsRuntimeAttributeDisableFatalOnOOM = 0x00000080, } }
using System.Linq; namespace EPI.DynamicProgramming { /// <summary> /// Count the number of ways to traverse a 2D array /// How many ways can you go from the top-left to the bottom-right in an n x m arrray? /// How would you count the number of ways in the presence of obstacles, specified by /// an n x m boolean 2D array B, where true represents an obstacle. /// </summary> public static class Number_Ways { /// <summary> /// Given the dimensons of A, n and m, return the number of ways from /// A[0][0] to A[n-1][m-1] /// </summary> /// <param name="n">row count</param> /// <param name="m">column count</param> /// <returns>Number of ways found</returns> public static int NumberOfWays(int n, int m) { if (n < m) { // swap n and m int temp = n; n = m; m = temp; } // initialize A[first row][0...m-1] with 1 int[] A = Enumerable.Repeat(1, m).ToArray(); for (int i = 1; i < n; i++) { int previous = 0; for (int j = 0; j < m; j++) { A[j] = A[j] + previous; previous = A[j]; } } return A[m - 1]; } /// <summary> /// Given the dimensons of A, n and m, and B return the number of ways from /// A[0][0] to A[n-1][m-1] considering obstacles /// </summary> /// <param name="n">row count</param> /// <param name="m">column count</param> /// <param name="B">obstacles represented as tre in 2D boolean array</param> /// <returns></returns> public static int NumberOfWaysWithObstacles(int n, int m, bool[,] B) { // initialize A[0..n-1][0...m-1] with 0 int[,] A = new int[n, m]; if (B[0, 0]) // No way to start from A[0,0] if B[0,0] == true { return 0; } A[0, 0] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!B[i, j]) { A[i, j] += (i < 1 ? 0 : A[i - 1, j]) + (j < 1 ? 0 : A[i, j - 1]); } } } return A[n - 1, m - 1]; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float pos; private Rigidbody rb; private boatController boat; //private float c_mass = 100, c_u_kx = 0., c_u_ky, c_gravity; //public Vector3 v_position, v_speed, v_acceleration; void Start () { rb = GetComponent<Rigidbody>(); boat = new boatController (Time.fixedDeltaTime); pos = 0; } void FixedUpdate () { float moveHorizontal = Input.GetAxis ("Horizontal"); //float moveVertical = Input.GetAxis ("Vertical"); if (moveHorizontal < 0) { boat.updateLinearVelocityWithForce (boat.c_forward_paddle_force); boat.updateAngularVelocityWithForceAndDistance (boat.c_forward_paddle_force, -0.9); } else if (moveHorizontal > 0){ boat.updateLinearVelocityWithForce (boat.c_forward_paddle_force); boat.updateAngularVelocityWithForceAndDistance (boat.c_forward_paddle_force, 0.9); } else { boat.updateLinearVelocityWithForce (0); boat.updateAngularVelocityWithForceAndDistance (0, 0); } boat.updateHeadingAndPosition (); //Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical); //rb.AddForce (movement * speed); //pos += moveHorizontal; //print("Heading %f, x %f, y %f", boat.heading, boat.position.x, boat.position.y); pos += 1; Vector3 p = new Vector3(boat.p_y, 0, boat.p_x); //print (boat.p_y); rb.MovePosition (p); } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag ("Pick Up")) { other.gameObject.SetActive (false); } } }
// File Prologue // Name: Darren Moody // CS 1400 Section 005 // Assignment: Project 11 // Date: 12/14/2013 // // // // I declare that the following code was written by me or provided // by the instructor for this project. I understand that copying source // code from any other source constitutes cheating, and that I will receive // a zero on this project if I am found in violation of this policy. // --------------------------------------------------------------------------- using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace project11 { public partial class Form1 : Form { const int SIZE = 10, ONE = 1, TWO = 2; private StreamReader dataStream; Stream myStream = null; int counter = 0, index = ONE; Employee[] myEmployees = new Employee[SIZE]; public Form1() { InitializeComponent(); } // The openToolStripMenuItem_Click() method // Purpose: reads employee data from text file and stores it in an array // Parameters: The object generating the event // and the event arguments // Returns: None private void openToolStripMenuItem_Click(object sender, EventArgs e) { string name = "", address = "", salaryVariables = ""; int empNumber = 0, hrs = 0; double wage; string[] salaryVar = new string[TWO]; string nextLine; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\" ; openFileDialog1.Filter = "text files (*.txt)|*txt" ; if(openFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = openFileDialog1.OpenFile()) != null) { dataStream = new StreamReader(myStream); do { nextLine = dataStream.ReadLine(); if (nextLine != null) { empNumber = int.Parse(nextLine); name = dataStream.ReadLine(); address = dataStream.ReadLine(); salaryVariables = dataStream.ReadLine(); salaryVar = salaryVariables.Split(); wage = double.Parse(salaryVar[0]); hrs = int.Parse(salaryVar[1]); myEmployees[counter] = new Employee(empNumber, name, address, wage, hrs); counter++; } } while (nextLine != null); } } // The next four lines will put the first value in the text boxes upon opening the file :) txtBoxName.Text = myEmployees[0].GetName(); txtBoxAddress.Text = myEmployees[0].GetAddress(); string initialSalaryText = string.Format("{0:C}", myEmployees[0].CalcSalary()); txtBoxPay.Text = initialSalaryText; } // The aboutToolStripMenuItem_Click() method // Purpose: To open a message box showing my information // Parameters: The object generating the event // and the event arguments // Returns: None private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Darren Moody\nCS1400-005\nProject #11"); } // The exitToolStripMenuItem_Click method // Purpose: To close the window and terminate the application // Parameters: The object generating the event // and the event arguments // Returns: None private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } // The btnNext_Click() method // Purpose: goes to the next employee's information // Parameters: The object generating the event // and the event arguments // Returns: None private void btnNext_Click(object sender, EventArgs e) { string otCheck, done; if (index >= counter) { done = "End of employee data!"; txtBoxName.Text = done; txtBoxAddress.Clear(); txtBoxPay.Clear(); } if (index < counter) { txtBoxName.Text = myEmployees[index].GetName(); txtBoxAddress.Text = myEmployees[index].GetAddress(); if (myEmployees[index].CheckForOT() == true) otCheck = string.Format("{0:C} - Worked OT!", myEmployees[index].CalcSalary()); // Display message if employee worked OT hrs else otCheck = string.Format("{0:C}", myEmployees[index].CalcSalary()); txtBoxPay.Text = otCheck; } index++; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class NextStage : MonoBehaviour { // Start is called before the first frame update public void Next() { if (puzzlesetting.puzzletype == 3) { SceneManager.LoadScene("SampleScene"); } if (puzzlesetting.puzzletype == 4) { SceneManager.LoadScene("4piece"); } if (puzzlesetting.puzzletype == 5) { SceneManager.LoadScene("5pieces"); } } public void Nextstage() { if(StageLoad.Stagetype == 1) { SceneManager.LoadScene("Stage1"); } if (StageLoad.Stagetype == 2) { SceneManager.LoadScene("Stage_Hard"); } } public void Back() { StageData_Hard.puzzlecheck = 0; StageData.puzzlecheck = 0; SceneManager.LoadScene("MainMenu"); } public void Gallery() { StageData_Hard.puzzlecheck = 0; StageData.puzzlecheck = 0; SceneManager.LoadScene("Gallery"); } }
using Ninject; using SoftUniStore.App.Data.Contracts; using SoftUniStore.App.DepedencyContainer; namespace SoftUniStore.App.Services { public abstract class Service { public Service() { this.Context = DependencyKernel.Kernel.Get<IUnitOfWork>(); } protected IUnitOfWork Context { get; } } }
using System; using System.Collections.Generic; using System.Text; using Domain.Data.DataModels; using Domain.Data.ViewModels; using Services.Abstractions.Transformators; namespace Services.Implementations.Transformators { public class UserTransformator : IUserTransformator { public UserFullViewModel ToUserFullViewModel(Users user) { return new UserFullViewModel { Id = user.Id, Name = $"{user.LastName} {user.FirstName} {user.Patronimic}", Age = (int) ((DateTime.Now - user.YearOfBirth).TotalDays / 365.2425) }; } public UserViewModel ToUserViewModel(Users user) { try { return new UserViewModel { Name = $"{user.LastName} {user.FirstName} {user.Patronimic}", Age = (int) ((DateTime.Now - user.YearOfBirth).TotalDays / 365.2425) }; } catch (Exception) { return null; } } } }
using System.Threading.Tasks; using FrontDesk.Api; using FrontDesk.Infrastructure.Data; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Moq; using Xunit; namespace IntegrationTests { [Collection("Sequential")] public abstract class BaseEfRepoTestFixture { protected AppDbContext _dbContext; protected BaseEfRepoTestFixture() { } protected static DbContextOptions<AppDbContext> CreateInMemoryContextOptions() { // Create a fresh service provider, and therefore a fresh // InMemory database instance. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Create a new options instance telling the context to use an // InMemory database and the new service provider. var builder = new DbContextOptionsBuilder<AppDbContext>(); builder.UseInMemoryDatabase("TestFrontDesk") .UseInternalServiceProvider(serviceProvider); return builder.Options; } protected DbContextOptions<AppDbContext> CreateSqlLiteOptions() { var builder = new DbContextOptionsBuilder<AppDbContext>(); builder.UseSqlite("DataSource=file:memdb1?mode=memory"); return builder.Options; } protected async Task<EfRepository> GetRepositoryAsync() { //var options = CreateInMemoryContextOptions(); var options = CreateSqlLiteOptions(); var mockMediator = new Mock<IMediator>(); _dbContext = new TestContext(options, mockMediator.Object); var logger = new LoggerFactory().CreateLogger<AppDbContextSeed>(); var appDbContextSeed = new AppDbContextSeed(_dbContext, logger); await appDbContextSeed.SeedAsync(new OfficeSettings().TestDate); return new EfRepository(_dbContext); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace REvE.Configuration.Tests.Models { [DataContract] public class ComplexItem { [DataMember] public List<ComplexItemFieldValue> ComplexFields { get; set; } } [Flags] public enum ComplexItemFieldValue { None = 0, One = 1 << 0, Two = 1 << 1, Three = One | Two } }
using Microsoft.EntityFrameworkCore.Migrations; namespace TimeSheetApplication.Migrations { public partial class MadeChangeinRolesandEmployeeTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "ID", table: "Roles", newName: "RoleID"); migrationBuilder.AddColumn<int>( name: "RoleID", table: "Employees", type: "int", nullable: false, defaultValue: 0); migrationBuilder.CreateIndex( name: "IX_Employees_RoleID", table: "Employees", column: "RoleID"); migrationBuilder.AddForeignKey( name: "FK_Employees_Roles_RoleID", table: "Employees", column: "RoleID", principalTable: "Roles", principalColumn: "RoleID", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Employees_Roles_RoleID", table: "Employees"); migrationBuilder.DropIndex( name: "IX_Employees_RoleID", table: "Employees"); migrationBuilder.DropColumn( name: "RoleID", table: "Employees"); migrationBuilder.RenameColumn( name: "RoleID", table: "Roles", newName: "ID"); } } }
using System; using System.Collections.Generic; namespace IrsMonkeyApi.Models.DB { public partial class ResolutionControl { public Guid ResolutionControlId { get; set; } public int? FormResolutionId { get; set; } public int? FormQuestionId { get; set; } public int? FormControlType { get; set; } public string FormControl { get; set; } public string Label { get; set; } public FormControlType FormControlTypeNavigation { get; set; } } }
namespace SimpleMVC.App.MVC.Controllers { using System.Runtime.CompilerServices; using Interfaces; using Interfaces.Generic; using ViewEngine; using ViewEngine.Generic; public abstract class Controller { protected Controller() { } protected IActionResult View([CallerMemberName] string caller = "") { string controllerName = this.GetType() .Name .Replace(MvcContext.Current.ControllersSuffix, string.Empty); string fullQualifiedName = string.Format($"{MvcContext.Current.AssemblyName}." + $"{MvcContext.Current.ViewsFolder}." + $"{controllerName}.") + $"{caller}"; return new ActionResult(fullQualifiedName); } protected IActionResult View(string controller, string action) { string fullQualifiedName = string.Format($"{MvcContext.Current.AssemblyName}." + $"{MvcContext.Current.ViewsFolder}." + $"{controller}." + $"{action}"); return new ActionResult(fullQualifiedName); } protected IActionResult<T> View<T>(T model, [CallerMemberName] string caller = "") { string controllerName = this.GetType() .Name .Replace(MvcContext.Current.ControllersSuffix, string.Empty); string fullQualifiedName = string.Format($"{MvcContext.Current.AssemblyName}." + $"{MvcContext.Current.ViewsFolder}." + $"{controllerName}.") + $"{caller}"; return new ActionResult<T>(fullQualifiedName, model); } protected IActionResult<T> View<T>(T model, string controller, string action) { string fullQualifiedName = string.Format($"{MvcContext.Current.AssemblyName}." + $"{MvcContext.Current.ViewsFolder}." + $"{controller}." + $"{action}"); return new ActionResult<T>(fullQualifiedName, model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ToDoListApplication.BusinessLayer.Entities; namespace ToDoListApplication.BusinessLayer.Repositories.Data { public class PersonsData : IEntityData { public List<Person> Persons { get; private set; } public PersonsData() { Persons = new List<Person> { new Person{ Id = 1, Name = "Juan Perez", PersonalId = "23423421", Email = "jperez@gmail.com" }, new Person{ Id = 2, Name = "Carlos Garcia", PersonalId = "30675989", Email = "cgarcia@gmail.com" }, new Person{ Id = 3, Name = "Mario Gomez", PersonalId = "21548734", Email = "mgomez@hotmail.com" }, new Person{ Id = 4, Name = "Alberto Rodriguez", PersonalId = "8471434", Email = "arodriguez@gmail.com" } }; } public void AddRange(IEnumerable<Person> list) { Persons.AddRange(list); } public void Add(Person entity) { Persons.Add(entity); } public bool Remove(Person entity) { return Persons.Remove(entity); } } }
// This file has been generated by the GUI designer. Do not modify. public partial class MainWindow { private global::Gtk.VPaned vpaned1; private global::Gtk.Fixed fixed1; private global::Gtk.Entry entry4; private global::Gtk.Entry entry5; private global::Gtk.Label label2; private global::Gtk.Label label3; private global::Gtk.Button button1; private global::Gtk.Button button2; private global::Gtk.Button button3; private global::Gtk.Button button4; private global::Gtk.Button button5; private global::Gtk.Label label4; private global::Gtk.Label label5; private global::Gtk.Label label6; private global::Gtk.Label label7; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget MainWindow this.Name = "MainWindow"; this.Title = global::Mono.Unix.Catalog.GetString ("Bitwise Operations"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); // Container child MainWindow.Gtk.Container+ContainerChild this.vpaned1 = new global::Gtk.VPaned (); this.vpaned1.CanFocus = true; this.vpaned1.Name = "vpaned1"; this.vpaned1.Position = 10; // Container child vpaned1.Gtk.Paned+PanedChild this.fixed1 = new global::Gtk.Fixed (); this.fixed1.Name = "fixed1"; this.fixed1.HasWindow = false; // Container child fixed1.Gtk.Fixed+FixedChild this.entry4 = new global::Gtk.Entry (); this.entry4.CanFocus = true; this.entry4.Name = "entry4"; this.entry4.IsEditable = true; this.entry4.InvisibleChar = '•'; this.fixed1.Add (this.entry4); global::Gtk.Fixed.FixedChild w1 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.entry4])); w1.X = 83; w1.Y = 31; // Container child fixed1.Gtk.Fixed+FixedChild this.entry5 = new global::Gtk.Entry (); this.entry5.CanFocus = true; this.entry5.Name = "entry5"; this.entry5.IsEditable = true; this.entry5.InvisibleChar = '•'; this.fixed1.Add (this.entry5); global::Gtk.Fixed.FixedChild w2 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.entry5])); w2.X = 83; w2.Y = 71; // Container child fixed1.Gtk.Fixed+FixedChild this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Integer 1"); this.fixed1.Add (this.label2); global::Gtk.Fixed.FixedChild w3 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.label2])); w3.X = 13; w3.Y = 33; // Container child fixed1.Gtk.Fixed+FixedChild this.label3 = new global::Gtk.Label (); this.label3.Name = "label3"; this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("Integer 2"); this.fixed1.Add (this.label3); global::Gtk.Fixed.FixedChild w4 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.label3])); w4.X = 14; w4.Y = 75; // Container child fixed1.Gtk.Fixed+FixedChild this.button1 = new global::Gtk.Button (); this.button1.WidthRequest = 50; this.button1.CanFocus = true; this.button1.Name = "button1"; this.button1.UseUnderline = true; this.button1.Label = global::Mono.Unix.Catalog.GetString ("Clear"); this.fixed1.Add (this.button1); global::Gtk.Fixed.FixedChild w5 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.button1])); w5.X = 83; w5.Y = 126; // Container child fixed1.Gtk.Fixed+FixedChild this.button2 = new global::Gtk.Button (); this.button2.WidthRequest = 50; this.button2.CanFocus = true; this.button2.Name = "button2"; this.button2.UseUnderline = true; this.button2.Label = global::Mono.Unix.Catalog.GetString ("Exit"); this.fixed1.Add (this.button2); global::Gtk.Fixed.FixedChild w6 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.button2])); w6.X = 83; w6.Y = 162; // Container child fixed1.Gtk.Fixed+FixedChild this.button3 = new global::Gtk.Button (); this.button3.WidthRequest = 40; this.button3.CanFocus = true; this.button3.Name = "button3"; this.button3.UseUnderline = true; this.button3.Label = global::Mono.Unix.Catalog.GetString ("And"); this.fixed1.Add (this.button3); global::Gtk.Fixed.FixedChild w7 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.button3])); w7.X = 150; w7.Y = 162; // Container child fixed1.Gtk.Fixed+FixedChild this.button4 = new global::Gtk.Button (); this.button4.WidthRequest = 40; this.button4.CanFocus = true; this.button4.Name = "button4"; this.button4.UseUnderline = true; this.button4.Label = global::Mono.Unix.Catalog.GetString ("Or"); this.fixed1.Add (this.button4); global::Gtk.Fixed.FixedChild w8 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.button4])); w8.X = 208; w8.Y = 162; // Container child fixed1.Gtk.Fixed+FixedChild this.button5 = new global::Gtk.Button (); this.button5.WidthRequest = 40; this.button5.CanFocus = true; this.button5.Name = "button5"; this.button5.UseUnderline = true; this.button5.Label = global::Mono.Unix.Catalog.GetString ("XOr"); this.fixed1.Add (this.button5); global::Gtk.Fixed.FixedChild w9 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.button5])); w9.X = 266; w9.Y = 162; // Container child fixed1.Gtk.Fixed+FixedChild this.label4 = new global::Gtk.Label (); this.label4.Name = "label4"; this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("Bits"); this.fixed1.Add (this.label4); global::Gtk.Fixed.FixedChild w10 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.label4])); w10.X = 389; w10.Y = 12; // Container child fixed1.Gtk.Fixed+FixedChild this.label5 = new global::Gtk.Label (); this.label5.Name = "label5"; this.label5.LabelProp = global::Mono.Unix.Catalog.GetString ("label5"); this.fixed1.Add (this.label5); global::Gtk.Fixed.FixedChild w11 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.label5])); w11.X = 382; w11.Y = 37; // Container child fixed1.Gtk.Fixed+FixedChild this.label6 = new global::Gtk.Label (); this.label6.Name = "label6"; this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("label6"); this.fixed1.Add (this.label6); global::Gtk.Fixed.FixedChild w12 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.label6])); w12.X = 382; w12.Y = 70; // Container child fixed1.Gtk.Fixed+FixedChild this.label7 = new global::Gtk.Label (); this.label7.Name = "label7"; this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("label7"); this.fixed1.Add (this.label7); global::Gtk.Fixed.FixedChild w13 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.label7])); w13.X = 382; w13.Y = 108; this.vpaned1.Add (this.fixed1); this.Add (this.vpaned1); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 721; this.DefaultHeight = 235; this.Show (); this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent); this.entry4.Changed += new global::System.EventHandler (this.OnEntry4Changed); this.entry5.Changed += new global::System.EventHandler (this.OnEntry5Changed); this.button1.Pressed += new global::System.EventHandler (this.OnButton1Pressed); this.button2.Pressed += new global::System.EventHandler (this.OnButton2Pressed); this.button3.Pressed += new global::System.EventHandler (this.OnButton3Pressed); this.button4.Pressed += new global::System.EventHandler (this.OnButton4Pressed); this.button5.Pressed += new global::System.EventHandler (this.OnButton5Pressed); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MathApplication.Models { public class MathQuestion { int correctAnswer; String operation; public MathQuestion(int givenCorrectAnswer, String givenOperation) { correctAnswer = givenCorrectAnswer; operation = givenOperation; } public int getCorrectAnswer() { return correctAnswer; } public String getOperation() { return operation; } } }
using Animals.Exeptions; using Animals.Models; using System; namespace Animals { public class StartUp { public static void Main() { var animalType = Console.ReadLine(); while (animalType != "Beast!") { try { var animalParams = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var name = animalParams[0]; var gender = animalParams[2]; int age; if (!int.TryParse(animalParams[1], out age)) { throw new InvalidInputExeptions(); } switch (animalType) { case "Cat": var cat = new Cat(name, age, gender); Console.WriteLine(cat); break; case "Kitten": var kitten = new Kitten(name, age); Console.WriteLine(kitten); break; case "Tomcat": var tomcat = new Tomcat(name, age); Console.WriteLine(tomcat); break; case "Frog": var frog = new Frog(name, age, gender); Console.WriteLine(frog); break; case "Dog": var dog = new Dog(name, age, gender); Console.WriteLine(dog); break; default: throw new InvalidInputExeptions(); } } catch (InvalidInputExeptions e) { Console.WriteLine(e.Message); } animalType = Console.ReadLine(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pin : MonoBehaviour { public float standingThreshold = 10f; public float distanceToRaise = 40f; private Rigidbody rigidbody; private void Awake() { this.GetComponent<Rigidbody>().solverVelocityIterations = 10; } // Use this for initialization void Start () { rigidbody = GetComponent<Rigidbody>(); } // Update is called once per frame void Update () { //print(name + IsStanding()); } public bool IsStanding() { //print(transform.rotation.eulerAngles); Vector3 rotationInEuler = transform.rotation.eulerAngles; float tiltInX = Mathf.Abs(rotationInEuler.x); float tiltInZ = Mathf.Abs(rotationInEuler.z); //print(tiltInX +" "+ tiltInZ); if(tiltInX < standingThreshold || tiltInZ < standingThreshold) { return true; } return false; } public void Raise() { //raise standing pins only by the distanceToRaise if (IsStanding()) { rigidbody.useGravity = false; transform.Translate(new Vector3(0f, distanceToRaise, 0f), Space.World); } Debug.Log("Raising pins"); } public void Lower() { if (IsStanding()) { transform.Translate(new Vector3(0f, -distanceToRaise, 0f), Space.World); rigidbody.useGravity = true; rigidbody.freezeRotation = true; } Debug.Log("Lower pins"); } public void ResetPin() { if (gameObject) { rigidbody.freezeRotation = false; rigidbody.useGravity = true; } } //One solution to remove the pins when they leave play area //private void OnTriggerExit(Collider collider) //{ // if (collider.gameObject.GetComponent<PinSetter>()) // { // Destroy(gameObject); // } //} }
using System.Collections; // GENERATED CODE. public class TrackedBundleVersion { public static readonly string bundleIdentifier = "mio.game.tilemaster"; public static readonly TrackedBundleVersionInfo Version_1_0_0 = new TrackedBundleVersionInfo ("1.0", 0); public static readonly TrackedBundleVersionInfo Version_1_0_1_1 = new TrackedBundleVersionInfo ("1.0.1", 1); public static readonly TrackedBundleVersionInfo Version_1_1_2 = new TrackedBundleVersionInfo ("1.1", 2); public static readonly TrackedBundleVersionInfo Version_1_2_3 = new TrackedBundleVersionInfo ("1.2", 3); public static readonly TrackedBundleVersionInfo Version_1_3_4 = new TrackedBundleVersionInfo ("1.3", 4); public static readonly TrackedBundleVersionInfo Version_1_3_1_5 = new TrackedBundleVersionInfo ("1.3.1", 5); public static readonly TrackedBundleVersionInfo Version_1_5_1_6 = new TrackedBundleVersionInfo ("1.5.1", 6); public static readonly TrackedBundleVersionInfo Version_1_7 = new TrackedBundleVersionInfo ("1", 7); public static readonly TrackedBundleVersion Instance = new TrackedBundleVersion (); public static TrackedBundleVersionInfo Current { get { return Instance.current; } } public static int CurrentBuildVersion { get { return 1; } } public ArrayList history = new ArrayList (); public TrackedBundleVersionInfo current = Version_1_7; public TrackedBundleVersion() { history.Add (Version_1_0_0); history.Add (Version_1_0_1_1); history.Add (Version_1_1_2); history.Add (Version_1_2_3); history.Add (Version_1_3_4); history.Add (Version_1_3_1_5); history.Add (Version_1_5_1_6); history.Add (current); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace MileCode { public class SceneViewTest : Editor { [MenuItem("MileTool/SceneView01")] public static void fun1() { //DrawCameraMode drawMode = DrawCameraMode.Wireframe; //SceneView.lastActiveSceneView.cameraMode = SceneView.GetBuiltinCameraMode(DrawCameraMode.Normal); SceneView sv = SceneView.lastActiveSceneView; //sv.MoveToView(); //sv.camera.enabled = false; Debug.Log(sv.camera.transform.rotation); sv.camera.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0)); Debug.Log(sv.camera.transform.rotation); if(sv != null) { //Debug.Log(sv.cameraMode.drawMode.ToString()); } } } }
using UnityEngine; using System.Collections; public class PaperController : MonoBehaviour { [SerializeField] private Vector3 effectsProps; [SerializeField] private Vector3[] effectsPropsPref; [SerializeField] private int myValue; [SerializeField] private GameObject[] Stamps; public void SetValue(int value) { myValue = value; effectsProps = effectsPropsPref[myValue]; ActivedStamps(); } public Vector3 GetEffectsProps() { return effectsProps; } void ActivedStamps() { if (effectsProps.x != 0) { Stamps[0].SetActive(true); if (effectsProps.x > 0) Stamps[3].SetActive(true); else Stamps[4].SetActive(true); } if (effectsProps.y != 0) { Stamps[1].SetActive(true); if (effectsProps.y > 0) Stamps[3].SetActive(true); else Stamps[4].SetActive(true); } if (effectsProps.z != 0) { Stamps[2].SetActive(true); if (effectsProps.z > 0) Stamps[3].SetActive(true); else Stamps[4].SetActive(true); } } }
using System.Windows; namespace WpfAppParking.View { public partial class DetailParkingenWindow : Window { public DetailParkingenWindow() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace DDMedi { public sealed class BaseDescriptor { public Type RegisterType { get; internal set; } public Type ImplementType { get; internal set; } public SupplierLifetime Lifetime { get; internal set; } public Func<IServiceProvider, object> GetInstance { get; internal set; } } public interface IBaseDescriptorCollection: IDisposable { IReadOnlyList<BaseDescriptor> Descriptors { get; } } internal interface IInternalBaseDescriptorCollection : IBaseDescriptorCollection { void AddIDDBroker(); void AddDDMediFactory(DDMediFactory factory); BaseDescriptor Create(Type implementType, SupplierLifetime lifetime); } internal class BaseDescriptorCollection : IInternalBaseDescriptorCollection { List<BaseDescriptor> _descriptors; public IReadOnlyList<BaseDescriptor> Descriptors => _descriptors; internal BaseDescriptorCollection() { _descriptors = new List<BaseDescriptor>(); } public void AddIDDBroker() { _descriptors.Insert(0, new BaseDescriptor { Lifetime = SupplierLifetime.Scoped, RegisterType = TypeConstant.IDDBrokerType, ImplementType = typeof(DDBroker) }); } public void AddDDMediFactory(DDMediFactory factory) { _descriptors.Insert(0, new BaseDescriptor { Lifetime = SupplierLifetime.Singleton, RegisterType = typeof(DDMediFactory), GetInstance = (provider) => { factory.SetScopeFactory(provider.GetService(typeof(ISupplierScopeFactory)) as ISupplierScopeFactory); return factory; } }); } public BaseDescriptor Create(Type implementType, SupplierLifetime lifetime) { var descriptor = _descriptors.FirstOrDefault(e => e.ImplementType == implementType); if(descriptor == null) { descriptor = new BaseDescriptor { Lifetime = lifetime, RegisterType = implementType, ImplementType = implementType }; _descriptors.Add(descriptor); return descriptor; } if (lifetime > descriptor.Lifetime) descriptor.Lifetime = lifetime; return descriptor; } public void Dispose() { _descriptors = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Win32 { public static class DeviceManagement { public static IEnumerable<DeviceInformation> AllDevices() => new DeviceInformationSet().Devices; public static IEnumerable<DeviceInformation> DevicesBySetupClass(Guid setupClassGuid) => new DeviceInformationSet(setupClassGuid).Devices; public static IEnumerable<DeviceInformation> DevicesByInterfaceClass(Guid interfaceClassGuid) => new DeviceInformationSet(interfaceClassGuid, DiGetClassFlags.DIGCF_ALLCLASSES | DiGetClassFlags.DIGCF_DEVICEINTERFACE).Devices; public static class SetupClasses { public static readonly Guid Battery = new Guid("{72631e54-78a4-11d0-bcf7-00aa00b7b32a}"); public static readonly Guid Biometric = new Guid("{53D29EF7-377C-4D14-864B-EB3A85769359}"); public static readonly Guid Bluetooth = new Guid("{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}"); public static readonly Guid Camera = new Guid("{ca3e7ab9-b4c3-4ae6-8251-579ef933890f}"); public static readonly Guid CdRom = new Guid("{4d36e965-e325-11ce-bfc1-08002be10318}"); public static readonly Guid Disk = new Guid("{4d36e967-e325-11ce-bfc1-08002be10318}"); public static readonly Guid DisplayAdapter = new Guid("{4d36e968-e325-11ce-bfc1-08002be10318}"); public static readonly Guid ExtensionInf = new Guid("{e2f84ce7-8efa-411c-aa69-97454ca4cb57}"); public static readonly Guid FloppyDiskController = new Guid("{4d36e969-e325-11ce-bfc1-08002be10318}"); public static readonly Guid FloppyDiskDrive = new Guid("{4d36e980-e325-11ce-bfc1-08002be10318}"); public static readonly Guid HardDiskController = new Guid("{4d36e96a-e325-11ce-bfc1-08002be10318}"); public static readonly Guid HumanInterface = new Guid("{745a17a0-74d3-11d0-b6fe-00a0c90f57da}"); public static readonly Guid Ieee1284dot4 = new Guid("{48721b56-6795-11d2-b1a8-0080c72e74a2}"); } public static class InterfaceClasses { public static class Storage { public static readonly Guid Disk = new Guid(0x53f56307, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid CdRom = new Guid(0x53f56308, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid Partition = new Guid(0x53f5630a, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid Tape = new Guid(0x53f5630b, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid WriteOnceDisk = new Guid(0x53f5630c, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid Volume = new Guid(0x53f5630d, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid MediumChanger = new Guid(0x53f56310, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid Floppy = new Guid(0x53f56311, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid CdChanger = new Guid(0x53f56312, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid StoragePort = new Guid(0x2accfe60, 0xc130, 0x11d2, 0xb0, 0x82, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b); public static readonly Guid VMLUN = new Guid(0x6f416619, 0x9f29, 0x42a5, 0xb2, 0x0b, 0x37, 0xe2, 0x19, 0xca, 0x02, 0xb0); public static readonly Guid SES = new Guid(0x1790c9ec, 0x47d5, 0x4df3, 0xb5, 0xaf, 0x9a, 0xdf, 0x3c, 0xf2, 0x3e, 0x48); } public static class USB { public static readonly Guid Hub = new Guid(0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8); public static readonly Guid Device = new Guid(0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED); public static readonly Guid HostController = new Guid(0x3abf6f2d, 0x71c4, 0x462a, 0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27); public static readonly Guid WmiStdData = new Guid(0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2); public static readonly Guid WmiStdNotification = new Guid(0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2); public static readonly Guid WmiDevicePerfInfo = new Guid(0x66c1aa3c, 0x499f, 0x49a0, 0xa9, 0xa5, 0x61, 0xe2, 0x35, 0x9f, 0x64, 0x7); public static readonly Guid WmiNodeInfo = new Guid(0x9c179357, 0xdc7a, 0x4f41, 0xb6, 0x6b, 0x32, 0x3b, 0x9d, 0xdc, 0xb5, 0xb1); public static readonly Guid WmiTracing = new Guid(0x3a61881b, 0xb4e6, 0x4bf9, 0xae, 0xf, 0x3c, 0xd8, 0xf3, 0x94, 0xe5, 0x2f); public static readonly Guid TransferTracing = new Guid(0x681eb8aa, 0x403d, 0x452c, 0x9f, 0x8a, 0xf0, 0x61, 0x6f, 0xac, 0x95, 0x40); public static readonly Guid PerformanceTracing = new Guid(0xd5de77a6, 0x6ae9, 0x425c, 0xb1, 0xe2, 0xf5, 0x61, 0x5f, 0xd3, 0x48, 0xa9); public static readonly Guid WmiSurpriseRemovalNotification = new Guid(0x9bbbf831, 0xa2f2, 0x43b4, 0x96, 0xd1, 0x86, 0x94, 0x4b, 0x59, 0x14, 0xb3); } } } }
using System.Drawing; using System.Windows.Forms; namespace Com.Colin.Win.Customized { public partial class TransparentControl : UserControl { public TransparentControl() { InitializeComponent(); } private void TransparencyButton_Paint(object sender, PaintEventArgs e) { this.BackColor = Color.Transparent;//使当前控件透明 } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IStateBase { // 初期化 void Init(Monster monster); // 更新 void Update(Monster monster); }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using CIPMSBC; public partial class Enrollment_Habonim_Tavor_Summary : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { btnReturnAdmin.Click += new EventHandler(btnReturnAdmin_Click); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int resultCampId = 0; //long resultFedID; if (Session["CampID"] != null) { Int32.TryParse(Session["CampID"].ToString(), out resultCampId); } else if (Session["FJCID"] != null) { DataSet ds = new CamperApplication().getCamperAnswers(Session["FJCID"].ToString(), "10", "10", "N"); if (ds.Tables[0].Rows.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; Int32.TryParse(dr["Answer"].ToString(), out resultCampId); } } string campID = resultCampId.ToString(); string last3digits = campID.Substring(campID.Length - 3); switch (last3digits) { case "029": imgLogo.Src = "../../images/Camp Galil.jpg"; break; case "036": imgLogo.Src = "../../images/Camp Gesher.jpg"; break; case "037": imgLogo.Src = "../../images/Camp Gilboa.jpg"; break; case "057": imgLogo.Src = "../../images/Camp Miriam.JPG"; break; case "060": imgLogo.Src = "../../images/Camp Moshava.jpg"; break; case "066": imgLogo.Src = "../../images/Camp Na'aleh.jpg"; break; case "095": imgLogo.Src = "../../images/Camp Tavor.jpg"; break; } if (resultCampId != 0 && resultCampId == 1133) { /*DataSet ds = new DataSet(); ds = new General().GetFederationCampContactDetails(resultFedID.ToString(), resultCampId.ToString()); if (ds.Tables[0].Rows.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; spnCampName.InnerText = "At " + dr["Name"].ToString().Trim().Replace('-',' ') + ", t"; }*/ //spnCampName.InnerText = "At URJ Camp Newman Swig, the award is available to any camp-age child in grades 3-12 who registers at one of the listed URJ Camps, and who is attending a non-profit Jewish sleep-away camp for at least 12 days for the first time. If the camper attends a session that is 19 days or longer, he/she is eligible for a grant of $1,000. If the camper attends a session that is 12-18 days, he she is eligible for a prorated grant of $700. Siblings from a single family are eligible to receive separate grants. The award is available regardless of need or whether the camper or camperís family has received other scholarship or financial aid."; } else if (resultCampId != 0 && resultCampId == 1132) { // spnCampName.InnerText = "At URJ Camp Kalsman, the award is available to any camp-age child in grades 3-12 who registers at one of the listed URJ Camps, and who is attending a non-profit Jewish sleep-away camp for at least 12 days for the first time. If the camper attends a session that is 19 days or longer, he/she is eligible for a grant of $1,000. If the camper attends a session that is 12-18 days, he she is eligible for a prorated grant of $700. Siblings from a single family are eligible to receive separate grants. The award is available regardless of need or whether the camper or camperís family has received other scholarship or financial aid."; } } } protected void btnPrevious_Click(object sender, EventArgs e) { Response.Redirect("../Step1_NL.aspx"); } protected void btnNext_Click(object sender, EventArgs e) { Response.Redirect("Step2_2.aspx?camp=tavor"); } protected void btnReturnAdmin_Click(object sender, EventArgs e) { string strRedirURL; try { strRedirURL = ConfigurationManager.AppSettings["AdminRedirURL"].ToString(); Response.Redirect(strRedirURL); } catch (Exception ex) { Response.Write(ex.Message); } } }
using LearnLanguages.Common.Enums.Autonomous; using LearnLanguages.Common.Exceptions; using LearnLanguages.Common.Interfaces.Autonomous; using System; using System.Net; using System.Threading.Tasks; using System.Windows; namespace LearnLanguages.Autonomous { [Serializable] public class AppDomainContext : MarshalByRefObject, IAutonomousServiceContext { public AppDomainContext() { } public void Abort() { throw new NotImplementedException(); } public int AllowedAbortTime { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public int AllowedExecuteTime { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public int AllowedLoadTime { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public Task ExecuteAsync() { throw new NotImplementedException(); } public IAutonomousService Service { get; private set; } public AutonomousServiceContextStates State { get; private set;} public bool TryLoadService(IAutonomousService service, int timeAllowedInMs) { State = AutonomousServiceContextStates.Loading; try { if (!service.IsEnabled) throw new ServiceNotEnabledException(service.Name, null); service.Load(timeAllowedInMs); } catch (Exception ex) { //Don't care what the exception is as far as the flow of code is concerned. //Log the error, though not sure how to do that with the app domain. State = AutonomousServiceContextStates.LoadError; } State = AutonomousServiceContextStates.Loaded; return true; } public Task AbortAsync(int timeAllowedInMs) { throw new NotImplementedException(); } public Task ExecuteAsync(int timeAllowedInMs) { throw new NotImplementedException(); } public Task KillAsync(int timeAllowedInMs) { throw new NotImplementedException(); } #region IDisposable Members public void Dispose() { Service = null; GC.Collect(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace ToolsQaStoreProject.Pages { public class HomePage : BaseNavigationMenuPage { private ReadOnlyCollection<IWebElement> _slideSelectorBtns => driver.FindElements(By.CssSelector("ul#slide_menu a")); private ReadOnlyCollection<IWebElement> _slideHeaders => driver.FindElements(By.ClassName("product_description")); public IWebDriver driver; public HomePage(IWebDriver driver) : base(driver) { this.driver = driver; } public bool HomePageTitle(string title) { return driver.WaitForPageTitle(title); } public bool CarouselSlideDisplayed(string slideProduct) { int slide = 0; _slideSelectorBtns[slide].Click(); var displayedHeader = _slideHeaders.FirstOrDefault(x => x.Displayed).Text; while (!displayedHeader.Equals(slideProduct)) { _slideSelectorBtns[slide].Click(); Thread.Sleep(1000); displayedHeader = _slideHeaders.FirstOrDefault(x => x.Displayed).Text; if (displayedHeader.StartsWith(slideProduct)) { return true; } slide++; if (slide > 2) { return false; } } return true; } } }
using UnityEngine; using System.Collections; public class TurnOnFlashlight : MonoBehaviour { private Light lt; // Use this for initialization void Start () { lt = GetComponent<Light>(); lt.intensity = 0; } public void turnOn() { lt.intensity = 5; } // Update is called once per frame void Update () { } }
using Microsoft.Xna.Framework; using System; namespace TwilightShards.Common { class GeneralFunctions { public static string FirstLetterToUpper(string str) { if (String.IsNullOrEmpty(str)) throw new ArgumentException("ARGH!"); if (str.Length > 1) return char.ToUpper(str[0]) + str.Substring(1); return str.ToUpper(); } public static double ConvCtF(double temp) => ((temp * 1.8) + 32); public static double ConvFtC(double temp) => ((temp - 32) / 1.8); public static double ConvCtK(double temp) => (temp + 273.15); public static double ConvFtK(double temp) => ((temp + 459.67) * (5.0 / 9.0)); public static double ConvKtC(double temp) => (temp - 273.15); public static double ConvKtF(double temp) => ((temp * 1.8) - 459.67); public static bool ContainsOnlyMatchingFlags(Enum enumType, int FlagVal) { int enumVal = Convert.ToInt32(enumType); if (enumVal == FlagVal) { return true; } return false; } public static double DegreeToRadians(double deg) => deg * (Math.PI / 180); public static double RadiansToDegree(double rad) => (rad * 180) / Math.PI; public static string ConvMinToHrMin(double val) { int hour = (int)Math.Floor(val / 60.0); double min = val - (hour * 60); return $"{hour}h{min.ToString("00")}m"; } public static Color GetRGBFromTemp(double temp) { float r,g,b = 0.0f; float effTemp = (float)Math.Min(Math.Max(temp, 1000), 40000); effTemp = effTemp / 100; //calc red if (effTemp <= 66) r = 255f; else { float x = effTemp -55f; r = 351.97690566805693f + (0.114206453784165f*x) - (40.25366309332127f * (float)Math.Log(x)); } //clamp red r = (float)Math.Min(Math.Max(r, 0), 255); //calc green if (effTemp <= 66) { float x = effTemp - 2f; g = -155.25485562709179f - (.44596950469579133f * x) + (104.49216199393888f * (float)Math.Log(x)); } else { float x = effTemp - 50f; g = 325.4494125711974f + (.07943456536662342f * x) - (28.0852963507957f * (float)Math.Log(x)); } //clamp green g = (float)Math.Min(Math.Max(g,0), 255); //calc blue if (effTemp <= 19) b = 0; else if (effTemp >= 66) b = 255; else { float x = effTemp - 10f; b = -254.76935184120902f + (.8274096064007395f * x) + (115.67994401066147f * (float)Math.Log(x)); } //clamp blue b = (float)Math.Min(Math.Max(b, 0), 255); Color ourColor = new Color((uint)r, (uint)g, (uint)b); ourColor.R = (byte)r; ourColor.G = (byte)g; ourColor.B = (byte)b; return ourColor; } private static Color CalculateMaskFromColor(Color target) { return new Color(255 - target.R, 255 - target.G, 255 - target.B); } } }
using Engine2D.Physics; using OpenTK.Mathematics; using System; using System.Collections.Generic; using System.Text; namespace Engine2D { public class RigidBodyComponent : Component { public float Mass { get; set; } = 1f; public BodyType Type { get; set; } = BodyType.DYNAMIC; public ChipmunkSharp.cpBody RigidBody { get; set; } public RigidBodyComponent() { } public void AddForce(Vector2 force) { } } public enum BodyType { DYNAMIC = ChipmunkSharp.cpBodyType.DYNAMIC, STATIC = ChipmunkSharp.cpBodyType.STATIC, KINEMATIC = ChipmunkSharp.cpBodyType.KINEMATIC, } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Text; using ET.Interface; namespace ET.Main { //模块载入器类 public class Modules : IDictionary<String, ICommModule> { [ImportMany("ETModule", AllowRecomposition = true)] private IEnumerable<Lazy<ICommModule, Dictionary<string, object>>> _modules; private Dictionary<String, ICommModule> _ms= new Dictionary<String, ICommModule>(); public void InitialModules() { var catalog = new DirectoryCatalog("Modules"); var container = new CompositionContainer(catalog); var objectToSatisfy = this; container.ComposeParts(this); var _msatt = new List<ModuleHeaderAttribute>(); foreach (var m in _modules) { var mt = new ModuleHeaderAttribute { ModuleKey = m.Metadata["ModuleKey"].ToString(), ModuleShowName = m.Metadata["ModuleShowName"].ToString(), ILevel = (Int32)m.Metadata["ILevel"], IsOnlyOneFile = (bool)m.Metadata["IsOnlyOneFile"] }; mt.ModuleIcon = m.Value.ModuleIcon; mt.FileIcon = m.Value.FileIcon; _msatt.Add(mt); _ms.Add(m.Metadata["ModuleKey"].ToString(), m.Value); } ModulesHeaders = _msatt; } public List<ModuleHeaderAttribute> ModulesHeaders { get; private set; } #region --IDictionary-- public ICommModule this[string key] { get => _ms[key]; } ICommModule IDictionary<string, ICommModule>.this[string key] { get => _ms[key]; set => throw new NotImplementedException(); } public ICollection<string> Keys => _ms.Keys; public ICollection<ICommModule> Values => _ms.Values; public int Count => _ms.Count; public bool IsReadOnly => true; public void Add(string key, ICommModule value) { throw new NotImplementedException(); } public void Add(KeyValuePair<string, ICommModule> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<string, ICommModule> item) { throw new NotImplementedException(); } public bool ContainsKey(string key) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<string, ICommModule>[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<string, ICommModule>> GetEnumerator() { return _ms.GetEnumerator(); } public bool Remove(string key) { throw new NotImplementedException(); } public bool Remove(KeyValuePair<string, ICommModule> item) { throw new NotImplementedException(); } public bool TryGetValue(string key, out ICommModule value) { return _ms.TryGetValue(key,out value); } IEnumerator IEnumerable.GetEnumerator() { return _ms.GetEnumerator(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RPC.SQLAPI { public enum ResultContainerKind { NoResult, Single, List } }
using System.Reflection; using System.Xml.Serialization; using Witsml.Xml; namespace Witsml.Data { [XmlRoot("capClients", Namespace = "http://www.witsml.org/schemas/1series")] public class WitsmlClientCapabilitiesRoot { [XmlAttribute("version")] public string Version = "1.4.1"; [XmlElement("capClient")] public WitsmlClientCapabilities ClientCapabilities { get; init; } } public class WitsmlClientCapabilities { [XmlAttribute("apiVers")] public string ApiVersion = "1.4.1"; [XmlElement("contact")] public ClientContactInformation Contact { get; init; } [XmlElement("description")] public string Description { get; init; } [XmlElement("name")] public string Name { get; init; } [XmlElement("vendor")] public string Vendor { get; init; } [XmlElement("version")] public string Version { get; init; } [XmlElement("schemaVersion")] public string SchemaVersion = "1.3.1.1,1.4.1.1"; public string ToXml() { var capClients = new WitsmlClientCapabilitiesRoot {ClientCapabilities = this}; return XmlHelper.Serialize(capClients); } } public class ClientContactInformation { [XmlElement("name")] public string Name { get; init; } [XmlElement("email")] public string Email { get; init; } [XmlElement("phone")] public string Phone { get; init; } } }
namespace BettingSystem.Domain.Betting.Models { public class ModelConstants { public class Bet { public const decimal MinAmountValue = decimal.One; public const decimal MaxAmountValue = decimal.MaxValue; } public class Gambler { public const decimal MinAmountValue = decimal.One; public const decimal MaxAmountValue = decimal.MaxValue; public const decimal MinDepositWithdrawValue = 10; public const decimal MaxDepositWithdrawValue = decimal.MaxValue; public const decimal MinBalanceValue = decimal.Zero; public const decimal MaxBalanceValue = decimal.MaxValue; } } }
using System; using System.Diagnostics; class MyGCCollectClass { private const int maxGarbage = 3; static void Main() { // Put some objects in memory. // Console.WriteLine("Sleeping for 20 sec PID {0}\n", Process.GetCurrentProcess().Id); //System.Threading.Thread.Sleep(10000); //Console.WriteLine("Finished Sleeping\n"); //System.Threading.Thread.Sleep(15000); for (int i = 0; i < 2145000000; i++) { int a, b=0; a = b + 2; } MakeSomeGarbage(); /*Console.WriteLine("Memory used before collection: {0:N0}", GC.GetTotalMemory(false)); // Collect all generations of memory.*/ MakeSomeGarbage(); //GC.Collect(); /*Console.WriteLine("Memory used after full collection: {0:N0}", GC.GetTotalMemory(true));*/ Console.WriteLine("Done"); } static int[] array; static void MakeSomeGarbage() { Version vt; array = new int[2]; // Create objects and release them to fill up memory with unused objects. for(int i = 0; i < 5; i++) { int j = MakeSomeGarbage0(); for (;j > 0; j--) { int k = array[j]; } } } static int MakeSomeGarbage0() { Version vt; GC.Collect(); // Create objects and release them to fill up memory with unused objects. /*for(int i = 0; i < maxGarbage; i++) { vt = new Version(); }*/ array = new int[4]; return 4-1; } } // The output from the example resembles the following: // Memory used before collection: 79,392 // Memory used after full collection: 52,640
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.MySchool { class SchoolClass { //Fields private List<Student> students; private List<Teacher> teachers; private List<String> comments; private string id; //Properties public Student[] Students { get { return this.students.ToArray(); } private set { } } public Teacher[] Teachers { get { return this.teachers.ToArray(); } private set { } } public string Id { get { return this.id; } set { this.id = value; } } public string[] Comments { get { return this.comments.ToArray(); } } //Constructors public SchoolClass(Student[] students, Teacher[] teachers, string id) { this.students = new List<Student>(students); this.teachers = new List<Teacher>(teachers); this.id = id; this.comments = new List<string>(); } //Methods public void AddStudent(Student student) { this.students.Add(student); } public void RemoveStudent(Student student) { this.students.Remove(student); } public void AddTeacher(Teacher teacher) { this.teachers.Add(teacher); } public void RemoveTeacher(Teacher teacher) { this.teachers.Remove(teacher); } public void AddComment(string comment) { this.comments.Add(comment); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Wintellect.PowerCollections; namespace FreeContentCatalogApplication { public class FreeContentCatalog { public static void Main() { StringBuilder output = new StringBuilder(); Catalog catalog = new Catalog(); ICommandExecutor commandExecutor = new CommandExecutor(); foreach (ICommand item in ParseCommands()) { commandExecutor.ExecuteCommand(catalog, item, output); } //redirect console FileStream ostrm; StreamWriter writer; TextWriter oldOut = Console.Out; try { ostrm = new FileStream("C:/Users/User/Desktop/Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write); writer = new StreamWriter(ostrm); } catch (Exception e) { Console.WriteLine("Cannot open Redirect.txt for writing"); Console.WriteLine(e.Message); return; } Console.SetOut(writer); Console.WriteLine(output); Console.SetOut(oldOut); writer.Close(); ostrm.Close(); Console.Write(output); } private static List<ICommand> ParseCommands() { List<ICommand> instructions = new List<ICommand>(); bool end = false; do { string userInput = Console.ReadLine(); end = (userInput.Trim() == "End"); if (!end) { instructions.Add(new Command(userInput)); } } while (!end); return instructions; } } public class CommandExecutor : ICommandExecutor { public void ExecuteCommand(ICatalog catalogContent, ICommand command, StringBuilder output) { switch (command.Type) { case CommandType.AddBook: catalogContent.Add(new Content(ContentItem.Book, command.Parameters)); output.AppendLine("Books Added"); break; case CommandType.AddMovie: catalogContent.Add(new Content(ContentItem.Movie, command.Parameters)); output.AppendLine("Movie added"); break; case CommandType.AddSong: catalogContent.Add(new Content(ContentItem.Song, command.Parameters)); output.Append("Song added"); break; case CommandType.AddApplication: catalogContent.Add(new Content(ContentItem.Application, command.Parameters)); output.AppendLine("Application added"); break; case CommandType.Update: if (command.Parameters.Length == 2) { output.AppendLine(String.Format("{0} items updated", catalogContent.UpdateContent(command.Parameters[0], command.Parameters[1]) - 1)); } else { throw new FormatException("Incorrect parameters for this command!"); } break; case CommandType.Find: if (command.Parameters.Length != 2) { throw new ArgumentException("Invalid number of parameters!"); } int numberOfElementsToList = int.Parse(command.Parameters[1]); IEnumerable<IContent> foundContent = catalogContent.GetListContent(command.Parameters[0], numberOfElementsToList); if (foundContent.Count() == 0) { output.AppendLine("No items found"); } else { foreach (IContent content in foundContent) { output.AppendLine(content.TextRepresentation); } } break; default: { throw new ArgumentException("Unknown command!"); } } } } class Catalog : ICatalog { private OrderedMultiDictionary<string, IContent> titles; private MultiDictionary<string, IContent> url; public Catalog() { //allowDuplicateValues this.titles = new OrderedMultiDictionary<string, IContent>(true); this.url = new MultiDictionary<string, IContent>(true); } public void Add(IContent content) { this.titles.Add(content.Title, content); this.url.Add(content.URL, content); } public IEnumerable<IContent> GetListContent(string title, int numberOfContentElements) { var contentToList = from c in this.titles[title] select c; return contentToList.Take(numberOfContentElements); } public int UpdateContent(string oldUrl, string newUrl) { int theElements = 0; //todo: test and refactor!!!! List<IContent> contentToList = this.url[oldUrl].ToList(); foreach (Content content in contentToList) { this.titles.Remove(content.Title, content); theElements++; //increase updatedElements } this.url.Remove(oldUrl); foreach (IContent content in contentToList) { content.URL = newUrl; } //again foreach (IContent content in contentToList) { this.titles.Add(content.Title, content); this.url.Add(content.URL, content); } return theElements; } } public class Content : IComparable, IContent { private string url; public string Title { get; set; } public string Author { get; set; } public Int64 Size { get; set; } public string URL { get { return this.url; } set { this.url = value; } } public ContentItem Type { get; set; } public string TextRepresentation { get { return this.ToString(); } set { this.TextRepresentation = ToString(); } } public Content(ContentItem type, string[] commandParams) { this.Type = type; this.Title = commandParams[(int)ContentAttributes.Title]; //todo: !? this.Author = commandParams[(int)ContentAttributes.Author]; this.Size = int.Parse(commandParams[(int)ContentAttributes.Size]); this.URL = commandParams[(int)ContentAttributes.Url]; } public int CompareTo(object otherObj) { if (otherObj == null) { throw new ArgumentNullException("Object to be compared with can't be null!"); } Content otherContent = otherObj as Content; if (otherContent != null) { int comparisonResult = this.TextRepresentation.CompareTo(otherContent.ToString()); return comparisonResult; } throw new ArgumentException("Object is not a Content"); } public override string ToString() { string output = String.Format("{0}: {1}; {2}; {3}; {4}", this.Type.ToString(), this.Title, this.Author, this.Size, this.URL); return output; } } public class Command : ICommand { readonly char[] paramsSeparators = { ';' }; readonly char commandEnd = ':'; public CommandType Type { get; set; } public string OriginalForm { get; set; } public string Name { get; set; } public string[] Parameters { get; set; } private Int32 commandNameEndIndex; public Command(string input) { this.OriginalForm = input.Trim(); this.Parse(); } private void Parse() { this.commandNameEndIndex = this.GetCommandNameEndIndex(); this.Name = this.ParseName(); this.Parameters = this.ParseParameters(); this.TrimParams(); this.Type = this.ParseCommandType(this.Name); } public CommandType ParseCommandType(string commandName) { CommandType type; if (commandName.Contains(':') || commandName.Contains(';')) { throw new FormatException("Not allowed chars in command!"); } switch (commandName.Trim()) { case "Add book": type = CommandType.AddBook; break; case "Add movie": type = CommandType.AddMovie; break; case "Add song": type = CommandType.AddSong; break; case "Add application": type = CommandType.AddApplication; break; case "Update": type = CommandType.Update; break; case "Find": type = CommandType.Find; break; default: { if (!commandName.ToLower().Contains("book") || !commandName.ToLower().Contains("movie") || !commandName.ToLower().Contains("song") || !commandName.ToLower().Contains("application")) { throw new ArgumentException("Not correct content type!"); } if (!commandName.ToLower().Contains("find") || !commandName.ToLower().Contains("update")) { throw new ArgumentException("Not correct command type!"); } throw new MissingFieldException("Invalid command name!"); } } return type; } public string ParseName() { string name = this.OriginalForm.Substring(0, this.commandNameEndIndex + 1); return name; } public string[] ParseParameters() { Int32 paramsLength = this.OriginalForm.Length - (this.commandNameEndIndex + 3); string paramsOriginalForm = this.OriginalForm.Substring(this.commandNameEndIndex + 3, paramsLength); string[] parameters = paramsOriginalForm.Split(paramsSeparators, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parameters.Length; i++) { parameters[i] = parameters[i]; } return parameters; } public Int32 GetCommandNameEndIndex() { Int32 endIndex = this.OriginalForm.IndexOf(commandEnd) - 1; return endIndex; } private void TrimParams() { for (int i = 0; i < this.Parameters.Length; i++) { this.Parameters[i] = this.Parameters[i].Trim(); } } public override string ToString() { string toString = String.Empty; foreach (string param in this.Parameters) { toString = this.Name + " " + param; } return toString; } } }
using UnityEngine; using System.Collections; public class GameDaoJiShiCtrl : MonoBehaviour { public UISprite TimeSprite; public TweenAlpha TimeTWAlpha; GameObject TimeObj; static GameDaoJiShiCtrl _Instance; public static GameDaoJiShiCtrl GetInstance() { return _Instance; } // Use this for initialization void Start() { _Instance = this; TimeObj = gameObject; TimeObj.SetActive(false); TimeTWAlpha.enabled = false; SetDaoJiShiNum(9); } public void SetDaoJiShiNum(int num) { TimeSprite.spriteName = "timeSub_" + num; if (num <= 0) { StopDaoJiShi(); } } public void StartPlayDaoJiShi() { if (TimeObj.activeSelf) { return; } TimeObj.SetActive(true); TimeTWAlpha.ResetToBeginning(); TimeTWAlpha.enabled = true; TimeTWAlpha.PlayForward(); } public void StopDaoJiShi() { if (!TimeObj.activeSelf) { return; } TimeObj.SetActive(false); TimeTWAlpha.enabled = false; SetDaoJiShiNum(9); } }
using System.Data.Entity.Validation; using System.Text; using CreateUser.Models; namespace CreateUser.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<UsersContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = false; } protected override void Seed(UsersContext context) { context.Towns.AddOrUpdate(t => t.Name,new Town() { Name = "Sofia", Country = "Bulgaria" }, new Town() { Name = "Berlin", Country = "Germany" }, new Town() { Name = "Vienna", Country = "Austria" }); SaveChanges(context); Town sofia = context.Towns.FirstOrDefault(t => t.Name == "Sofia"); Town berlin = context.Towns.FirstOrDefault(t => t.Name == "Berlin"); var user1 = new User() { Age = 12, Email = "avb@abv.bg", Id = 3, IsDeleted = false, LastTimeLoggedIn = DateTime.Now, Password = "Qww1@qwer", RegisteredOn = DateTime.Now.AddDays(-4), Username = "Asen", TownInBorn = sofia, TownInLiving = berlin, FirstName = "Ivan", LastName = "Ivanov" }; context.Users.AddOrUpdate(user1); SaveChanges(context); } private void SaveChanges(DbContext context) { try { context.SaveChanges(); } catch (DbEntityValidationException ex) { StringBuilder sb = new StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } throw new DbEntityValidationException( "Entity Validation Failed - errors follow:\n" + sb.ToString(), ex ); // Add the original exception as the innerException } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using ApiMocker.Entities; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ApiMocker { public class Program { public static void Main(string[] args) { var application = new CmdApplication(); application.ExecuteCmdApplication(args); CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) { var url = ApplicationSettings.Instance.Https ? "https" : "http"; return WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); }) //.UseSetting("https_port", ApplicationSettings.Instance.TcpPort.ToString()); .UseUrls($"{url}://*:{ApplicationSettings.Instance.TcpPort}"); } } }
using System; using System.Windows.Input; using BSMU_Schedule.ViewModels; namespace BSMU_Schedule.Commands { public class OpenMenuPageCommand: ICommand { public event EventHandler CanExecuteChanged; public ScheduleViewModel ViewModel { get; set; } public OpenMenuPageCommand(ScheduleViewModel viewModel) { ViewModel = viewModel; } public bool CanExecute(object parameter) { return true; } public async void Execute(object parameter) { await ViewModel.OpenMenuPage(); } } }
 using System; using System.Collections.Generic; using System.Linq; using alg; /* * tags: backtracking * Time(2^n), Space(n) */ namespace leetcode { public class Lc282_Expression_Add_Operators { /* * standard backtracking with corner cases: * 1. merge * 2. zero leading can't be merged * 3. integer overflow * 4. multiplication */ public IList<string> AddOperators(string num, int target) { var ret = new List<string>(); if (string.IsNullOrEmpty(num)) return ret; AddOperatorsBt(num, target, 0, "", ret, 0, 0); return ret; } void AddOperatorsBt(string str, long target, int pos, string path, IList<string> res, long value, long mul) { if (pos == str.Length) { if (value == target) res.Add(path); return; } for (int i = pos; i < str.Length; i++) { if (i != pos && str[pos] == '0') break; long cur = long.Parse(str.Substring(pos, i - pos + 1)); // merge if (pos == 0) { AddOperatorsBt(str, target, i + 1, path + cur, res, cur, cur); } else { AddOperatorsBt(str, target, i + 1, path + "+" + cur, res, value + cur, cur); AddOperatorsBt(str, target, i + 1, path + "-" + cur, res, value - cur, -cur); AddOperatorsBt(str, target, i + 1, path + "*" + cur, res, value - mul + cur * mul, cur * mul); } } } public void Test() { var exp = new string[] { "1+2+3", "1*2*3" }; Console.WriteLine(exp.SameSet(AddOperators("123", 6))); exp = new string[] { "2*3+2", "2+3*2" }; Console.WriteLine(exp.SameSet(AddOperators("232", 8))); exp = new string[] { "1*0+5", "10-5" }; Console.WriteLine(exp.SameSet(AddOperators("105", 5))); exp = new string[] { "0+0", "0-0", "0*0" }; Console.WriteLine(exp.SameSet(AddOperators("00", 0))); exp = new string[] { }; Console.WriteLine(exp.SameSet(AddOperators("3456237490", 9191))); Console.WriteLine(exp.SameSet(AddOperators("2147483648", -2147483648))); } } }
using System.Diagnostics; namespace Nono.Engine.Logging { public readonly struct Performance { public readonly double ElapsedMilliSeconds; public Performance(long startTicks, long endTicks) { ElapsedMilliSeconds = (endTicks - startTicks) / 1.0e4; } public override string ToString() => $"{ElapsedMilliSeconds:0.000}ms"; public static Performance Measure(long start) => new Performance(start, Stopwatch.GetTimestamp()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Data; using CreamBell_DMS_WebApps.App_Code; using Elmah; namespace CreamBell_DMS_WebApps { public partial class frmInvoiceSave : System.Web.UI.Page { CreamBell_DMS_WebApps.App_Code.Global baseObj = new Global(); string strmessage = string.Empty; public DataTable dtLineItems; SqlConnection conn = null; SqlCommand cmd, cmd1, cmd2; SqlTransaction transaction; string strQuery = string.Empty; int intApplicable; Boolean boolDiscAvalMRP = false; DataTable Msg = new DataTable(); public DataTable dtSchemeLineItems; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { #region SO Load btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";"); Session["InvSchemeLineItem"] = null; Session["InvLineItem"] = null; dtLineItems = null; ProductGroup(); FillProductCode(); if (Session["SO_NOList"] != null) { string sono = Session["SO_NOList"].ToString();// Cache["SO_NO"].ToString(); if (Session["SiteCode"] != null) { string siteid = Session["SiteCode"].ToString(); if (lblsite.Text == "") { lblsite.Text = siteid; } //==================For Warehouse Location============== CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); string query1 = "select MainWarehouse from ax.inventsite where siteid='" + Session["SiteCode"].ToString() + "'"; DataTable dt = new DataTable(); dt = obj.GetData(query1); if (dt.Rows.Count > 0) { Session["TransLocation"] = dt.Rows[0]["MainWarehouse"].ToString(); } } else { string siteid = "Select A.SiteId From ax.ACXLOADSHEETHEADER A where A.SO_NO in (select id from [dbo].[CommaDelimitedToTable]('" + sono + "' ,','))"; DataTable dt = new DataTable(); CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); dt = obj.GetData(siteid); if (dt.Rows.Count > 0) { lblsite.Text = dt.Rows[0]["SiteId"].ToString(); } } if (sono != "") { ShowData(sono); } txtInvoiceDate.Text = string.Format("{0:dd/MMM/yyyy }", DateTime.Today); // For Shceme Seletion DataTable dtApplicable = baseObj.GetData("SELECT APPLICABLESCHEMEDISCOUNT from AX.ACXCUSTMASTER WHERE CUSTOMER_CODE = '" + drpCustomerCode.SelectedValue.ToString() + "'"); if (dtApplicable.Rows.Count > 0) { intApplicable = Convert.ToInt32(dtApplicable.Rows[0]["APPLICABLESCHEMEDISCOUNT"].ToString()); } if (intApplicable == 1 || intApplicable == 3) { this.BindSchemeGrid(); } string strQuery = @"Select SchemeCode,Product_Code as ItemCode,cast(BOXQty as decimal(10,2)) as Qty,cast(PCSQty as decimal(10,2)) as QtyPcs,Slab from [ax].[ACXSALESLINE] Where SO_NO in ('" + sono + "') and SchemeCode<>'' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'"; DataTable dtScheme = baseObj.GetData(strQuery); if (dtScheme.Rows.Count > 0) { for (int i = 0; i <= dtScheme.Rows.Count - 1; i++) { GetSelectedShemeItemChecked(dtScheme.Rows[i]["SchemeCode"].ToString(), dtScheme.Rows[i]["ItemCode"].ToString(), Convert.ToInt16(Convert.ToDouble(dtScheme.Rows[i]["Qty"].ToString())), Convert.ToInt16(Convert.ToDouble(dtScheme.Rows[i]["Slab"].ToString())), Convert.ToInt16(Convert.ToDouble(dtScheme.Rows[i]["QtyPcs"].ToString()))); } } if (intApplicable == 1 || intApplicable == 3) { this.SchemeDiscCalculation(); DataTable dt1 = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt1 = (DataTable)Session["InvLineItem"]; } GridViewFooterCalculate(dt1); } } #endregion } catch(Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } } } private void ShowData(string sono) { DataTable dt = new DataTable(); CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); string query = " select A.SO_No,CONVERT(VARCHAR(11),A.SO_Date,106) as SO_Date ,A.Loadsheet_No,CONVERT(VARCHAR(11),L.LoadSheet_Date,106) as LoadSheet_Date, " + "B.CUST_GROUP,Customer_Group=(Select C.CUSTGROUP_NAME from ax.ACXCUSTGROUPMASTER C where C.CustGroup_Code=B.CUST_GROUP)," + "B.Customer_Code,concat(B.Customer_Code,'-', B.Customer_Name) as Customer_Name," + " B.Address1,B.Mobile_No,B.VAT,B.GSTINNO,B.GSTREGISTRATIONDATE,B.COMPOSITIONSCHEME,B.STATE " + " from [ax].[ACXSALESHEADER] A left join ax.Acxcustmaster B on A.Customer_Code=B.Customer_Code " + " left join ax.ACXLOADSHEETHEADER L on L.LoadSheet_No=A.LoadSheet_No and L.Siteid=A.siteid " + // " where A.[Siteid]='" + lblsite.Text + "' and A.SO_NO in (" + sono + " )"; " where A.[Siteid]='" + lblsite.Text + "' and A.SO_NO in (select id from [dbo].[CommaDelimitedToTable]('" + sono + "' ,','))"; dt = obj.GetData(query); if (dt.Rows.Count > 0) { drpCustomerGroup.Items.Insert(0, new ListItem(dt.Rows[0]["Customer_Group"].ToString(), dt.Rows[0]["CUST_GROUP"].ToString())); drpCustomerCode.Items.Insert(0, new ListItem(dt.Rows[0]["Customer_Name"].ToString(), dt.Rows[0]["Customer_Code"].ToString())); txtTIN.Text = dt.Rows[0]["VAT"].ToString(); txtAddress.Text = dt.Rows[0]["Address1"].ToString(); txtMobileNO.Text = dt.Rows[0]["Mobile_No"].ToString(); txtLoadSheetNumber.Text = dt.Rows[0]["Loadsheet_No"].ToString(); drpSONumber.Items.Insert(0, new ListItem(dt.Rows[0]["So_NO"].ToString(), dt.Rows[0]["So_NO"].ToString())); txtSODate.Text = dt.Rows[0]["SO_Date"].ToString(); txtLoadsheetDate.Text = dt.Rows[0]["LoadSheet_Date"].ToString(); /* ---------- GST Implementation Start ----------- */ txtGSTtin.Text = dt.Rows[0]["GSTINNO"].ToString(); txtGSTtinRegistration.Text = dt.Rows[0]["GSTREGISTRATIONDATE"].ToString(); chkCompositionScheme.Checked = Convert.ToBoolean(dt.Rows[0]["COMPOSITIONSCHEME"]); txtBillToState.Text = dt.Rows[0]["STATE"].ToString(); query = "EXEC USP_CUSTSHIPTOADDRESS '" + drpCustomerCode.SelectedValue + "'"; ddlShipToAddress.Items.Clear(); baseObj.BindToDropDown(ddlShipToAddress, query, "SHIPTOADDRESS", "SHIPTOADDRESS"); /*----------------GST Implementation End-------------------------- */ } else { txtGSTtin.Text = ""; txtGSTtinRegistration.Text = ""; ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('Record Not Found..')", true); } #region //query = "select GSTINNO,GSTREGISTRATIONDATE,COMPOSITIONSCHEME from VW_CUSTOMERGSTINFO where CUSTOMER_CODE='" + drpCustomerCode.SelectedValue + "'"; //DataTable dt1 = baseObj.GetData(query); //if (dt1.Rows.Count > 0) //{ // txtGSTtin.Text = dt1.Rows[0]["GSTINNO"].ToString(); // txtGSTtinRegistration.Text = dt1.Rows[0]["GSTREGISTRATIONDATE"].ToString(); // chkCompositionScheme.Checked = Convert.ToBoolean(dt1.Rows[0]["COMPOSITIONSCHEME"]); //} //else //{ // txtGSTtin.Text = ""; // txtGSTtinRegistration.Text = ""; //} #endregion conn = baseObj.GetConnection(); cmd2 = new SqlCommand("AX.ACX_SOTOINVOICECREATION"); //transaction = conn.BeginTransaction(); cmd2.Connection = conn; //cmd2.Transaction = transaction; cmd2.CommandTimeout = 0; cmd2.CommandType = CommandType.StoredProcedure; dt = new DataTable(); // dt = obj.GetData(query); cmd2.Parameters.Clear(); cmd2.Parameters.AddWithValue("@TransLocation", Session["TransLocation"].ToString()); string s = Session["TransLocation"].ToString(); cmd2.Parameters.AddWithValue("@siteid", lblsite.Text); cmd2.Parameters.AddWithValue("@so_no", sono); dt.Load(cmd2.ExecuteReader()); //transaction.Commit(); if (conn != null) { if (conn.State.ToString() == "Open") { conn.Close(); conn.Dispose(); } } //dt = obj.GetData(query); if (dt.Rows.Count > 0) { Session["InvLineItem"] = dt; gvDetails.DataSource = dt; gvDetails.DataBind(); GridViewFooterCalculate(dt); } else { gvDetails.DataSource = dt; gvDetails.DataBind(); } TDApplicable(); } private void TDApplicable() { string strTD = "select TDPEAPPLICABLE from [ax].[ACXCUSTGROUPMASTER] Where CustGroup_Code='" + drpCustomerGroup.SelectedItem.Value + "'"; DataTable dtTDApplicable = new DataTable(); dtTDApplicable = baseObj.GetData(strTD); if (dtTDApplicable != null) { if (dtTDApplicable.Rows[0]["TDPEAPPLICABLE"].ToString() == "1") { //gvDetails.Columns[11].Visible = false; txtTDValue.Enabled = true; btnApply.Enabled = true; } else { //gvDetails.Columns[11].Visible = true; txtTDValue.Enabled = false; btnApply.Enabled = false; } } } protected void txtRate_TextChanged(object sender, EventArgs e) { //DataTable dt = new DataTable(); //TextBox txtRate = (TextBox)sender; //GridViewRow row = (GridViewRow)txtRate.Parent.Parent; //decimal SchemeDiscVal = 0; //int idx = row.RowIndex; //TextBox qty = (TextBox)row.Cells[0].FindControl("txtBox"); //Label soqty = (Label)row.Cells[0].FindControl("SO_Qty"); //Label amt = (Label)row.Cells[0].FindControl("Amount"); //Label tax = (Label)row.Cells[0].FindControl("Tax"); //Label taxvalue = (Label)row.Cells[0].FindControl("TaxValue"); //Label lblSchemeDiscVal = (Label)row.Cells[0].FindControl("lblSchemeDiscVal"); //if (lblSchemeDiscVal.Text.Trim().Length > 0) //{ // SchemeDiscVal = Convert.ToDecimal(lblSchemeDiscVal.Text); //} //if (Convert.ToDecimal(txtRate.Text) <= 0) //{ // return; //} //if (qty.Text == "") //{ // decimal taxValue = (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(soqty.Text) * (Convert.ToDecimal(tax.Text) / 100)); // decimal amount = (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(soqty.Text)) + taxValue; // taxvalue.Text = taxValue.ToString("#.##"); // amt.Text = amount.ToString("#.##"); //} //else //{ // decimal taxValue = (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(qty.Text) * (Convert.ToDecimal(tax.Text) / 100)); // decimal amount = (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(qty.Text)) + taxValue; // // decimal amount = Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(qty.Text); // taxvalue.Text = taxValue.ToString("#.##"); // amt.Text = amount.ToString("#.##"); //} //UpdateSession(); } protected void txtBox_TextChanged(object sender, EventArgs e) { DataTable dt = new DataTable(); TextBox txtB = (TextBox)sender; decimal SchemeDiscVal = 0; GridViewRow row = (GridViewRow)txtB.Parent.Parent; CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); string query; int idx = row.RowIndex; // Label amt = (Label)row.Cells[0].FindControl("Amount"); HiddenField ddlPrCode = (HiddenField)row.Cells[0].FindControl("HiddenField2"); HiddenField discType = (HiddenField)row.FindControl("hDiscType"); HiddenField discCalculation = (HiddenField)row.FindControl("hDiscCalculationType"); HiddenField hClaimDiscAmt = (HiddenField)row.FindControl("hClaimDiscAmt"); Label lblLtr = (Label)row.FindControl("LTR"); Label amount = (Label)row.FindControl("Amount"); TextBox txtRate = (TextBox)row.FindControl("txtRate"); Label tax = (Label)row.FindControl("Tax"); Label taxvalue = (Label)row.FindControl("TaxValue"); Label AddtaxPer = (Label)row.FindControl("AddTax"); Label AddTaxValue = (Label)row.FindControl("AddTaxValue"); Label StockQty = (Label)row.FindControl("StockQty"); Label SO_Qty = (Label)row.FindControl("SO_Qty"); Label DiscPer = (Label)row.FindControl("Disc"); Label DiscVal = (Label)row.FindControl("DiscValue"); Label lblMRP = (Label)row.FindControl("MRP"); Label lblTotal = (Label)row.FindControl("Total"); TextBox SDiscPer = (TextBox)row.FindControl("SecDisc"); TextBox SDiscVal = (TextBox)row.FindControl("SecDiscValue"); boolDiscAvalMRP = false; TextBox txtBoxQtyGrid = (TextBox)row.FindControl("txtBoxQtyGrid"); TextBox txtPcsQtyGrid = (TextBox)row.FindControl("txtPcsQtyGrid"); TextBox txtBox = (TextBox)row.FindControl("txtBox"); Label txtBoxPcs = (Label)row.FindControl("txtBoxPcs"); HiddenField hdnTaxableammount = (HiddenField)row.FindControl("hdnTaxableAmount"); Label lblPack = (Label)row.FindControl("Pack"); Label lblSchemeDiscVal = (Label)row.FindControl("lblSchemeDiscVal"); if (lblSchemeDiscVal.Text.Trim().Length > 0) { SchemeDiscVal = Convert.ToDecimal(lblSchemeDiscVal.Text); } if ((Convert.ToDecimal(txtBoxQtyGrid.Text) + Convert.ToDecimal(txtPcsQtyGrid.Text)) <= 0) { lblLtr.Text = "0.00"; taxvalue.Text = "0.00"; amount.Text = "0.00"; lblTotal.Text = "0.00"; AddTaxValue.Text = "0.00"; DiscVal.Text = "0.00"; SDiscPer.Text = "0.00"; SDiscVal.Text = "0.00"; txtBoxPcs.Text = "0.00"; txtBox.Text = "0.00"; hdnTaxableammount.Value = "0.00"; row.BackColor = System.Drawing.Color.White; } else { if (Convert.ToDecimal(txtPcsQtyGrid.Text) > Convert.ToDecimal(lblPack.Text)) { int pcs = Convert.ToInt16(Convert.ToDecimal(txtPcsQtyGrid.Text));// Convert.ToInt16(txtPcsQtyGrid.Text); Math.Floor(pcsQty / packSize) int pac = Convert.ToInt16(Convert.ToDecimal(lblPack.Text)); int addbox = pcs / pac;//Convert.ToInt16(Convert.ToDecimal(lblPack.Text)); int remainder = pcs % pac; if (remainder == 0) { txtPcsQtyGrid.Text = "0"; } else { txtPcsQtyGrid.Text = Convert.ToString(remainder); } txtBoxQtyGrid.Text = Convert.ToString(Convert.ToInt16(Convert.ToDouble(txtBoxQtyGrid.Text)) + addbox); } int BoxQty = (txtBoxQtyGrid.Text.Trim() == "" ? 0 : Convert.ToInt16(Convert.ToDouble(txtBoxQtyGrid.Text))); //txtPcsQtyGrid.Text = (txtPcsQtyGrid.Text == "0.00" ? "0" : txtPcsQtyGrid.Text); txtPcsQtyGrid.Text = (Convert.ToInt16(Convert.ToDouble(txtPcsQtyGrid.Text)) == 0 ? "0" : txtPcsQtyGrid.Text); string BoxPcs = Convert.ToString(BoxQty) + '.' + (txtPcsQtyGrid.Text.Length == 1 ? "0" : "") + Convert.ToString(txtPcsQtyGrid.Text); txtBoxPcs.Text = BoxPcs; decimal SecDiscPer = Convert.ToDecimal(SDiscPer.Text); decimal SecDiscValue = Convert.ToDecimal(SDiscVal.Text); decimal decTotAmount = 0; if (Convert.ToDecimal(txtB.Text) > Convert.ToDecimal(StockQty.Text)) { row.BackColor = System.Drawing.Color.Red; txtB.Text = SO_Qty.Text; string message = "alert('Please Enter a valid number or input quantity less than stock quantity!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); txtBoxQtyGrid.Text = Convert.ToInt16(Convert.ToDecimal(SO_Qty.Text)).ToString(); decimal PcsQty, stPack, stSOQty; PcsQty = stPack = stSOQty = 0; stPack = Convert.ToInt16(Convert.ToDecimal(lblPack.Text)); stSOQty = Convert.ToInt16(Convert.ToDecimal(SO_Qty.Text)); PcsQty = (stSOQty - Convert.ToDecimal(SO_Qty.Text)) * stPack; if (PcsQty < 0) { txtBoxQtyGrid.Text = Convert.ToInt16(Convert.ToDecimal(SO_Qty.Text) - 1).ToString(); PcsQty = PcsQty * -1; } txtPcsQtyGrid.Text = PcsQty.ToString(); } else { row.BackColor = System.Drawing.Color.White; } if (Convert.ToDecimal(txtB.Text) > 0) { if (SecDiscPer != 0) { SecDiscValue = (SecDiscPer * (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(txtB.Text)) / 100); } DataTable dtscheme = new DataTable(); dtscheme = baseObj.GetData("EXEC USP_ACX_GetSalesLineCalcGST '" + ddlPrCode.Value.ToString() + "','" + drpCustomerCode.SelectedValue.ToString() + "','" + Session["SiteCode"].ToString() + "'," + Convert.ToDecimal(txtB.Text) + "," + Convert.ToDecimal(txtRate.Text) + ",'" + Session["SITELOCATION"].ToString() + "','" + drpCustomerGroup.SelectedValue.ToString() + "','" + Session["DATAAREAID"].ToString() + "'"); if (dtscheme.Rows.Count > 0) { if (dtscheme.Rows[0]["RETMSG"].ToString().IndexOf("TRUE") >= 0) { DiscVal.Text = dtscheme.Rows[0]["DISCVAL"].ToString(); hClaimDiscAmt.Value = dtscheme.Rows[0]["CLAIMDISCAMT"].ToString(); } } //if (discType.Value == "0") // Percentage //{ // DiscVal.Text = (Convert.ToDecimal(DiscPer.Text) * Convert.ToDecimal(txtB.Text) * Convert.ToDecimal(txtRate.Text) / 100).ToString("0.00"); //} } //if (discType.Value == "1") // value //{ // DiscVal.Text = (Convert.ToDecimal(DiscPer.Text) * Convert.ToDecimal(txtB.Text)).ToString("0.00"); // decimal discVal = 0; // decimal tax1 = 0, tax2 = 0; // //dt = new DataTable(); // //dt = baseObj.GetData("Select H.TaxValue,H.ACXADDITIONALTAXVALUE,H.ACXADDITIONALTAXBASIS from [ax].inventsite G inner join InventTax H on G.TaxGroup=H.TaxGroup where H.ItemId='" + ddlPrCode.Value + "' and G.Siteid='" + Session["SiteCode"].ToString() + "'"); // //if (txtBillToState.Text == "JK") // //{ // // if (dt.Rows.Count > 0) // // { // // tax1 = Convert.ToDecimal(dt.Rows[0]["TaxValue"].ToString()); // // tax2 = Convert.ToDecimal(dt.Rows[0]["ACXADDITIONALTAXVALUE"].ToString()); // // if (Convert.ToInt16(dt.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 0) // Tax On Tax // // { // // discVal = Convert.ToDecimal(DiscVal.Text) / (1 + (tax1 + (tax1 * tax2) / 100) / 100); // // } // // else // Tax On Taxable Amount // // { // // discVal = Convert.ToDecimal(DiscVal.Text) / (1 + ((tax1 + tax2) / 100)); // // } // // DiscVal.Text = Convert.ToString(discVal.ToString("0.00")); // // } // //} // //else // //{ // discVal = Convert.ToDecimal(DiscVal.Text) / (1 + ((Convert.ToDecimal(tax.Text) + Convert.ToDecimal(AddtaxPer.Text)) / 100)); // DiscVal.Text = Convert.ToString(discVal.ToString("0.00")); // //} //} query = "select CEILING(" + txtB.Text + "/(CASE WHEN ISNULL(A.Product_Crate_PackSize,0)=0 THEN 1 ELSE A.Product_Crate_PackSize END)) as Crates,(" + txtB.Text + "*A.Product_PackSize*A.Ltr)/1000 as Ltr from ax.InventTable A where A.ItemId='" + ddlPrCode.Value + "'"; dt = obj.GetData(query); if (dt.Rows.Count > 0) { decimal l; //decimal rate, amt; l = Convert.ToDecimal(dt.Rows[0]["Ltr"].ToString()); lblLtr.Text = l.ToString("#.##"); decimal taxV = 0; //if (boolDiscAvalMRP == true) //{ taxV = ((decTotAmount - Convert.ToDecimal(DiscVal.Text) - SecDiscValue) * (Convert.ToDecimal(tax.Text) / 100)); } //else { taxV = ((Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(txtB.Text) - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal) * (Convert.ToDecimal(tax.Text) / 100)); } DataTable dtTax = new DataTable(); decimal AddtaxV = 0; //if (txtBillToState.Text == "JK") //{ // dtTax = baseObj.GetData("Select H.TaxValue,H.ACXADDITIONALTAXVALUE,H.ACXADDITIONALTAXBASIS from [ax].inventsite G inner join InventTax H on G.TaxGroup=H.TaxGroup where H.ItemId='" + ddlPrCode.Value + "' and G.Siteid='" + Session["SiteCode"].ToString() + "'"); // if (dtTax.Rows.Count > 0) // { // if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 0) // Tax On Tax // { // AddtaxV = (taxV * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // else if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 1) // Tax On Taxable Amount // { // if (boolDiscAvalMRP == true) // { // AddtaxV = ((decTotAmount - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal) * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // else // { // AddtaxV = ((Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(txtB.Text) - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal) * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // } // else if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 2) // Tax On MRP // { // AddtaxV = ((Convert.ToDecimal(lblMRP.Text) * Convert.ToDecimal(txtB.Text) - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal) * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // else // { // AddtaxV = ((Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(txtB.Text) - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal) * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // } //} //else //{ AddtaxV = ((Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(txtB.Text) - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal) * (Convert.ToDecimal(AddtaxPer.Text) / 100)); //} decimal amt = 0; //if (boolDiscAvalMRP == true) //{ amt = (decTotAmount - Convert.ToDecimal(DiscVal.Text) - SecDiscValue + taxV + AddtaxV);} //else { amt = (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(txtB.Text)) - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal + taxV + AddtaxV; } hdnTaxableammount.Value = ((Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(txtB.Text)) - Convert.ToDecimal(DiscVal.Text) - SecDiscValue - SchemeDiscVal).ToString(); taxvalue.Text = taxV.ToString("#.##"); AddTaxValue.Text = AddtaxV.ToString("#.##"); amount.Text = amt.ToString("#.##"); lblTotal.Text = amt.ToString("#.##"); //SDiscVal.Text = SecDiscValue.ToString("#.##"); SDiscVal.Text = String.Format("{0:0.00}", SecDiscValue); //SecDiscValue.ToString("#.##"); SDiscPer.Text = String.Format("{0:0.00}", SecDiscPer); //SecDiscPer.ToString("#.##"); // } } else { lblLtr.Text = "0.00"; taxvalue.Text = "0.00"; amount.Text = "0.00"; lblTotal.Text = "0.00"; AddTaxValue.Text = "0.00"; DiscVal.Text = "0.00"; SDiscPer.Text = "0.00"; SDiscVal.Text = "0.00"; hdnTaxableammount.Value = "0.00"; // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Enter a valid number!!');", true); string message = "alert('Please Enter a valid number!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } } //have to update session TDCalculation(); GrandTotal(); UpdateSession(); // For Shceme Seletion DataTable dtApplicable = baseObj.GetData("SELECT APPLICABLESCHEMEDISCOUNT from AX.ACXCUSTMASTER WHERE CUSTOMER_CODE = '" + drpCustomerCode.SelectedValue.ToString() + "'"); if (dtApplicable.Rows.Count > 0) { intApplicable = Convert.ToInt32(dtApplicable.Rows[0]["APPLICABLESCHEMEDISCOUNT"].ToString()); } if (intApplicable == 1 || intApplicable == 3) { foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkgrd = (CheckBox)rw.FindControl("chkSelect"); TextBox txtQty = (TextBox)rw.FindControl("txtQty"); TextBox txtQtyPCS = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Text = ""; txtQtyPCS.Text = ""; chkgrd.Checked = false; } this.SchemeDiscCalculation(); BindSchemeGrid(); } this.SchemeDiscCalculation(); DataTable dt1 = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt1 = (DataTable)Session["InvLineItem"]; } GridViewFooterCalculate(dt1); // BindSchemeGrid(); } //protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e) //{ // gvDetails.PageIndex = e.NewPageIndex; // BindGridview(); //} public void GrandTotal() { //==================All gridview data into a datatable========== DataTable dtLine = new DataTable(); dtLine.Columns.Add("SO_Qty", typeof(decimal)); dtLine.Columns.Add("Invoice_Qty", typeof(decimal)); dtLine.Columns.Add("Box_Qty", typeof(decimal)); dtLine.Columns.Add("Pcs_Qty", typeof(decimal)); dtLine.Columns.Add("LTR", typeof(decimal)); dtLine.Columns.Add("DiscVal", typeof(decimal)); dtLine.Columns.Add("TaxValue", typeof(decimal)); dtLine.Columns.Add("ADDTaxValue", typeof(decimal)); dtLine.Columns.Add("Amount", typeof(decimal)); dtLine.Columns.Add("TD", typeof(decimal)); dtLine.Columns.Add("Total", typeof(decimal)); dtLine.Columns.Add("SecDiscAmount", typeof(decimal)); foreach (GridViewRow gvr in gvDetails.Rows) { Label SO_Qty = (Label)gvr.FindControl("SO_Qty"); TextBox Invoice_Qty = (TextBox)gvr.FindControl("txtBox"); TextBox Box_Qty = (TextBox)gvr.FindControl("txtBoxQtyGrid"); TextBox Pcs_Qty = (TextBox)gvr.FindControl("txtPcsQtyGrid"); Label Ltr = (Label)gvr.FindControl("LTR"); Label DiscVal = (Label)gvr.FindControl("DiscValue"); Label taxvalue = (Label)gvr.FindControl("TaxValue"); Label AddTaxValue = (Label)gvr.FindControl("AddTaxValue"); Label amount = (Label)gvr.FindControl("Amount"); Label lblTD = (Label)gvr.FindControl("TD"); Label lblTotal = (Label)gvr.FindControl("Total"); TextBox SecDiscVal = (TextBox)gvr.FindControl("SecDiscValue"); if (Invoice_Qty.Text == null || Invoice_Qty.Text == string.Empty) { Invoice_Qty.Text = "0.00"; } if (Box_Qty.Text == null || Box_Qty.Text == string.Empty) { Box_Qty.Text = "0.00"; } if (Pcs_Qty.Text == null || Pcs_Qty.Text == string.Empty) { Pcs_Qty.Text = "0.00"; } if (AddTaxValue.Text == string.Empty) { AddTaxValue.Text = "0.00"; } if (DiscVal.Text == string.Empty) { DiscVal.Text = "0.00"; } if (taxvalue.Text == "") { taxvalue.Text = "0.00"; } if (Ltr.Text == "") { Ltr.Text = "0"; } if (SO_Qty.Text == "") { SO_Qty.Text = "0"; } if (amount.Text == "") { amount.Text = "0.00"; } if (lblTD.Text == string.Empty) { lblTD.Text = "0.00"; } if (lblTotal.Text == string.Empty) { lblTotal.Text = "0.00"; } if (SecDiscVal.Text == string.Empty) { SecDiscVal.Text = "0.00"; } DataRow r; r = dtLine.NewRow(); r["So_Qty"] = Convert.ToDecimal(SO_Qty.Text); r["Invoice_Qty"] = Convert.ToDecimal(Invoice_Qty.Text); r["Box_Qty"] = Convert.ToDecimal(Box_Qty.Text); r["Pcs_Qty"] = Convert.ToDecimal(Pcs_Qty.Text); r["Ltr"] = Convert.ToDecimal(Ltr.Text); r["DiscVal"] = Convert.ToDecimal(DiscVal.Text); r["TaxValue"] = Convert.ToDecimal(taxvalue.Text); r["ADDTaxValue"] = Convert.ToDecimal(AddTaxValue.Text); r["Amount"] = Convert.ToDecimal(amount.Text); r["TD"] = Convert.ToDecimal(lblTD.Text); r["Total"] = Convert.ToDecimal(lblTotal.Text); r["SecDiscAmount"] = Convert.ToDecimal(SecDiscVal.Text); dtLine.Rows.Add(r); } GridViewFooterCalculate(dtLine); } protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { } protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e) { } protected void gvDetails_SelectedIndexChanged(object sender, EventArgs e) { } protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Label StockQty = (Label)e.Row.FindControl("StockQty"); TextBox BoxQty = (TextBox)e.Row.FindControl("txtBox"); if (Convert.ToDecimal(BoxQty.Text) > Convert.ToDecimal(StockQty.Text)) { e.Row.BackColor = System.Drawing.Color.Tomato; } // Pcs Billing Applicable HiddenField hdnPrCode = (HiddenField)e.Row.FindControl("HiddenField2"); TextBox PcsQty = (TextBox)e.Row.FindControl("txtPcsQtyGrid"); DataTable dt = baseObj.GetData("Select Product_Group from ax.InventTable where ItemId='" + hdnPrCode.Value + "'"); if (dt.Rows.Count > 0) { dt = baseObj.GetPcsBillingApplicability(Session["SCHSTATE"].ToString(), dt.Rows[0][0].ToString()); string ProductGroupApplicable = string.Empty; if (dt.Rows.Count > 0) { ProductGroupApplicable = dt.Rows[0][1].ToString(); } if (ProductGroupApplicable == "Y") { PcsQty.Enabled = true; } else { PcsQty.Enabled = false; } } } } protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e) { } public bool ValidateSchemeQty1(string SelectedShemeCode) { bool returnType = true; if (gvScheme.Rows.Count > 0) { DataTable dt = new DataTable(); dt.Columns.Add("SchemeCode", typeof(string)); dt.Columns.Add("Slab", typeof(int)); dt.Columns.Add("FreeQty", typeof(int)); dt.Columns.Add("FreeQtyPcs", typeof(int)); dt.Columns.Add("SetNO", typeof(int)); DataRow dr = null; foreach (GridViewRow rw in gvScheme.Rows) { TextBox txtQty = (TextBox)rw.FindControl("txtQty"); dr = dt.NewRow(); dr["SchemeCode"] = rw.Cells[1].Text; dr["Slab"] = Convert.ToInt16(rw.Cells[6].Text); dr["SetNo"] = Convert.ToInt16(rw.Cells[7].Text); if (rw.Cells[8].Text == "&nbsp;") { rw.Cells[8].Text = ""; } if (rw.Cells[11].Text == "&nbsp;") { rw.Cells[11].Text = ""; } if (rw.Cells[8].Text != "") { dr["FreeQty"] = Convert.ToInt16(Convert.ToInt16(rw.Cells[8].Text)); dr["FreeQtyPcs"] = 0; } if (Convert.ToString(rw.Cells[11].Text) != "") { dr["FreeQtyPcs"] = Convert.ToInt16(Convert.ToInt16(rw.Cells[11].Text)); dr["FreeQty"] = 0; } dt.Rows.Add(dr); } DataView dv = new DataView(dt); DataTable distinctTableValue = (DataTable)dv.ToTable(true, "SchemeCode", "Slab", "FreeQty", "FreeQtyPcs", "SetNo"); DataView dv1 = new DataView(distinctTableValue); dv1.RowFilter = "[SchemeCode]='" + SelectedShemeCode + "'"; if (dv1.Count > 0) { decimal TotalQty = 0, TotalQtyPcs = 0; decimal Slab = 0; decimal FreeQty = 0; decimal FreeQtyPcs = 0; decimal SetNo = 0; string SchemeCode = string.Empty; foreach (DataRowView drow in dv1) { TotalQty = 0; TotalQtyPcs = 0; SchemeCode = drow["SchemeCode"].ToString(); Slab = Convert.ToInt16(drow["Slab"]); FreeQty = Convert.ToInt16(drow["FreeQty"]); FreeQtyPcs = Convert.ToInt16(drow["FreeQtyPcs"]); foreach (GridViewRow rw in gvScheme.Rows) { //HiddenField hdnCalculationOn = (HiddenField)rw.FindControl("hdnCalculationOn"); CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); if (chkBx.Checked == true) { TextBox txtQty = (TextBox)rw.FindControl("txtQty"); TextBox txtQtyPcs = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Text = (txtQty.Text.Trim().Length == 0 ? "0" : txtQty.Text); txtQtyPcs.Text = (txtQtyPcs.Text.Trim().Length == 0 ? "0" : txtQtyPcs.Text); if (!string.IsNullOrEmpty(txtQty.Text) && rw.Cells[1].Text == SchemeCode && Convert.ToInt16(rw.Cells[6].Text) == Slab && Convert.ToInt16(rw.Cells[7].Text) == SetNo) { TotalQty += Convert.ToInt16(txtQty.Text); } if (!string.IsNullOrEmpty(txtQtyPcs.Text) && rw.Cells[1].Text == SchemeCode && Convert.ToInt16(rw.Cells[6].Text) == Slab && Convert.ToInt16(rw.Cells[7].Text) == SetNo) { TotalQtyPcs += Convert.ToInt16(txtQtyPcs.Text); } } } if (TotalQty != FreeQty && Slab == Convert.ToInt16(drow["Slab"]) && SetNo == Convert.ToInt16(drow["SetNo"]) && TotalQtyPcs != FreeQtyPcs) { returnType = false; } } } else { returnType = false; } } return returnType; } public bool ValidateSchemeQtyNew() { bool returnType = true; if (gvScheme.Rows.Count > 0) { DataTable dt = new DataTable(); dt.Columns.Add("SchemeCode", typeof(string)); dt.Columns.Add("Slab", typeof(int)); dt.Columns.Add("FreeQty", typeof(int)); DataRow dr = null; foreach (GridViewRow rw in gvScheme.Rows) { TextBox txtQty = (TextBox)rw.FindControl("txtQty"); dr = dt.NewRow(); dr["SchemeCode"] = rw.Cells[1].Text; dr["Slab"] = Convert.ToInt16(rw.Cells[6].Text); dr["FreeQty"] = Convert.ToInt16(Convert.ToInt16(rw.Cells[7].Text)); dt.Rows.Add(dr); } DataView dv = new DataView(dt); DataTable distinctTableValue = (DataTable)dv.ToTable(true, "SchemeCode", "Slab", "FreeQty"); decimal TotalQty = 0; decimal Slab = 0; decimal FreeQty = 0; string SchemeCode = string.Empty; foreach (DataRow drow in distinctTableValue.Rows) { TotalQty = 0; SchemeCode = drow["SchemeCode"].ToString(); Slab = Convert.ToInt16(drow["Slab"]); FreeQty = Convert.ToInt16(drow["FreeQty"]); foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); if (chkBx.Checked == true) { TextBox txtQty = (TextBox)rw.FindControl("txtQty"); if (!string.IsNullOrEmpty(txtQty.Text) && rw.Cells[1].Text == SchemeCode && Convert.ToInt16(rw.Cells[6].Text) == Slab) { TotalQty += Convert.ToInt16(txtQty.Text); } } } if (TotalQty != FreeQty && Slab == Convert.ToInt16(drow["Slab"])) { returnType = false; } } } return returnType; } protected void btnSave_Click(object sender, EventArgs e) { try { if (drpSONumber.Text=="") { Session["SO_NOList"] = null; Response.Redirect("~/frmInvoicePrepration.aspx"); } bool b = Validation(); if (!b) { return; } bool SchemeStock = checkStock(); if (SchemeStock == false) { string message = "alert('Please check stock qty for scheme product!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } string SelectedSchemeCode = string.Empty; foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chk = (CheckBox)rw.FindControl("ChkSelect"); if (chk.Checked) { SelectedSchemeCode = rw.Cells[1].Text; break; } } bool IsSchemeValidate = false; DataTable dtApplicable = baseObj.GetData("SELECT APPLICABLESCHEMEDISCOUNT from AX.ACXCUSTMASTER WHERE CUSTOMER_CODE = '" + drpCustomerCode.SelectedValue.ToString() + "'"); if (dtApplicable.Rows.Count > 0) { intApplicable = Convert.ToInt32(dtApplicable.Rows[0]["APPLICABLESCHEMEDISCOUNT"].ToString()); } if (intApplicable == 1 || intApplicable == 3) { IsSchemeValidate = baseObj.ValidateSchemeQty(SelectedSchemeCode, ref gvScheme); // ValidateSchemeQty(SelectedSchemeCode); } else { IsSchemeValidate = true; } if (IsSchemeValidate == true) { if (b == true) { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); if (strmessage == string.Empty) { SaveHeader(); string message = "alert('Invoice No: " + txtInvoiceNo.Text + " Saved Successfully!!'); window.location.href='frmInvoicePrepration.aspx'; "; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); ClearAll(); } } } else { string message = "alert('Free Quantity should be Equal !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } } public bool checkSchemeStock() { bool result = false; DataTable dtStock = new DataTable(); if (gvScheme.Rows.Count > 0) { foreach (GridViewRow gv in gvScheme.Rows) { if (((CheckBox)gv.FindControl("chkSelect")).Checked) { string Sproduct = gv.Cells[4].Text; TextBox txtQtyToAvail = (TextBox)gv.FindControl("txtQty"); string strStcok = "Select coalesce(cast(sum(F.TransQty) as decimal(10,2)),0) as TransQty from [ax].[ACXINVENTTRANS] F where F.[SiteCode]='" + Session["SiteCode"].ToString() + "' and F.[ProductCode]='" + Sproduct + "' and F.[TransLocation]='" + Session["TransLocation"].ToString() + "' "; dtStock = baseObj.GetData(strStcok); decimal curstock = 0; if (dtStock.Rows.Count > 0) { curstock = Convert.ToDecimal(dtStock.Rows[0]["TransQty"].ToString()); } if (curstock < Convert.ToDecimal(txtQtyToAvail.Text)) { result = false; } else { result = true; } } } } return result; } public bool checkStock() { bool result = true; DataTable dtLine = new DataTable(); DataTable dtStock = new DataTable(); DataColumn column = new DataColumn(); //-----------------------------------------------------------// dtLine = new DataTable("dtLine"); //dtLine.Columns.Add(column); // dtLineItems.Columns.Add("MaterialGroup", typeof(string)); dtLine.Columns.Add("Product_Code", typeof(string)); dtLine.Columns.Add("StockQty", typeof(decimal)); dtLine.Columns.Add("InvoiceQty", typeof(decimal)); foreach (GridViewRow gvD in gvDetails.Rows) { TextBox InvoiceQty = (TextBox)gvD.FindControl("txtBox"); Label lblStock = (Label)gvD.FindControl("StockQty"); HiddenField product = (HiddenField)gvD.FindControl("HiddenField2"); DataRow row; row = dtLine.NewRow(); row["Product_Code"] = product.Value; row["StockQty"] = lblStock.Text; row["InvoiceQty"] = InvoiceQty.Text; dtLine.Rows.Add(row); } if (gvScheme.Rows.Count > 0) { foreach (GridViewRow gv in gvScheme.Rows) { if (((CheckBox)gv.FindControl("chkSelect")).Checked) { string Sproduct = gv.Cells[4].Text; TextBox txtQtyToAvail = (TextBox)gv.FindControl("txtQty"); TextBox txtQtyToAvailPcs = (TextBox)gv.FindControl("txtQtyPcs"); txtQtyToAvail.Text = (txtQtyToAvail.Text.Trim().Length == 0 ? "0" : txtQtyToAvail.Text); txtQtyToAvailPcs.Text = (txtQtyToAvailPcs.Text.Trim().Length == 0 ? "0" : txtQtyToAvailPcs.Text); int packSize = 1, boxqty = 0, pcsQty = 0; decimal billQty = 0; using (DataTable dtFreeItem = baseObj.GetData("Select Cast(ISNULL(Product_PackSize,1) as int) AS Product_PackSize From AX.InventTable Where ItemId='" + gv.Cells[4].Text.ToString() + "'")) { if (dtFreeItem.Rows.Count > 0) { string strPack = dtFreeItem.Rows[0]["Product_PackSize"].ToString(); packSize = Convert.ToInt16(strPack); } } if (Convert.ToInt16(txtQtyToAvailPcs.Text) > 0) { pcsQty = Convert.ToInt32(txtQtyToAvailPcs.Text); } else { pcsQty = 0; } boxqty = Convert.ToInt32(pcsQty / packSize); pcsQty = pcsQty - (boxqty * packSize); boxqty = boxqty + Convert.ToInt32(txtQtyToAvail.Text); billQty = Math.Round(Convert.ToDecimal((boxqty + (pcsQty / packSize))), 2); string strStcok = "Select coalesce(cast(sum(F.TransQty) as decimal(10,2)),0) as TransQty from [ax].[ACXINVENTTRANS] F where F.[SiteCode]='" + Session["SiteCode"].ToString() + "' and F.[ProductCode]='" + Sproduct + "' and F.[TransLocation]='" + Session["TransLocation"].ToString() + "' "; dtStock = baseObj.GetData(strStcok); decimal curstock = 0; if (dtStock.Rows.Count > 0) { curstock = Convert.ToDecimal(dtStock.Rows[0]["TransQty"].ToString()); } DataRow row; row = dtLine.NewRow(); row["Product_Code"] = gv.Cells[4].Text; row["StockQty"] = curstock; row["InvoiceQty"] = billQty;// decimal.Parse(txtQtyToAvail.Text); dtLine.Rows.Add(row); } } } var stkresult = dtLine.AsEnumerable() .GroupBy(r => new { ProductCode = r.Field<String>("Product_Code"), }) .Select(g => { var row = g.First(); row.SetField("InvoiceQty", g.Sum(r => r.Field<Decimal>("InvoiceQty"))); return row; }) .CopyToDataTable(); dtLine = stkresult; string strSQL = ""; for (int i = 0; i < dtLine.Rows.Count; i++) { // ReCalculate Product Stock strSQL = "Select coalesce(CAST(SUM(F.TransQty) AS decimal(10,2)),0) AS TransQty FROM [AX].[ACXINVENTTRANS] F WHERE F.[SiteCode]='" + Session["SiteCode"].ToString() + "' AND F.[ProductCode]='" + dtLine.Rows[i]["Product_Code"].ToString() + "' AND F.[TransLocation]='" + Session["TransLocation"].ToString() + "' "; dtStock = baseObj.GetData(strSQL); decimal curstock = 0; if (dtStock.Rows.Count > 0) { curstock = Convert.ToDecimal(dtStock.Rows[0]["TransQty"].ToString()); } else { curstock = 0; } //decimal curStock = Convert.ToDecimal(dtLine.Rows[i]["StockQty"].ToString()); decimal invQty = Convert.ToDecimal(dtLine.Rows[i]["InvoiceQty"].ToString()); if (curstock < invQty) { result = false; } } return result; } public string InvoiceNo() { try { string IndNo = string.Empty; string Number = string.Empty; int intTotalRec; string strQuery = "SELECT ISNULL(MAX(CAST(RIGHT(Invoice_No,7) AS INT)),0)+1 AS new_InvoiceNo FROM [AX].[ACXSALEINVOICEHEADER] WHERE [Siteid]='" + lblsite.Text + "' AND TranType = 1"; DataTable dt = new DataTable(); CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); dt = obj.GetData(strQuery); intTotalRec = dt.Rows.Count; if (dt.Rows[0]["new_InvoiceNo"].ToString() != "0") { string st = dt.Rows[0]["new_InvoiceNo"].ToString(); if (st.Length < 7) { int len = st.Length; int plen = 7 - len; for (int i = 0; i < plen; i++) { st = "0" + st; } if (txtTIN.Text != "") { IndNo = "VI-" + st; } else { IndNo = "RI-" + st; } return IndNo; } } else { string st = "1"; if (st.Length < 7) { int len = st.Length; int plen = 7 - len; for (int i = 0; i < plen; i++) { st = "0" + st; } if (txtTIN.Text != "") { IndNo = "VI-" + st; } else { IndNo = "RI-" + st; } // IndNo = "RI-" + st; return IndNo; } } return IndNo; } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); strmessage = ex.Message.ToString(); return strmessage; } } public void SaveHeader() { try { List<string> ilist = new List<string>(); List<string> litem = new List<string>(); //string query; CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); DataTable dtNumSEQ = obj.GetNumSequenceNew(6, Session["SiteCode"].ToString(), Session["DATAAREAID"].ToString()); //st.Substring(st.Length - 6) + System.DateTime.Now.ToString("yyMMddhhmmss"); string SO_NO = string.Empty; string NUMSEQ = string.Empty; if (dtNumSEQ != null) { txtInvoiceNo.Text = dtNumSEQ.Rows[0][0].ToString(); NUMSEQ = dtNumSEQ.Rows[0][1].ToString(); } else { return; } DataTable dt = new DataTable(); //======Save Header=================== conn = obj.GetConnection(); cmd = new SqlCommand("ACX_SaleInvoice_Header"); transaction = conn.BeginTransaction(); cmd.Connection = conn; cmd.Transaction = transaction; cmd.CommandTimeout = 0; cmd.CommandType = CommandType.StoredProcedure; string sono = Session["SO_NOList"].ToString();//Cache["SO_NO"].ToString(); cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString()); cmd.Parameters.AddWithValue("@SITEID", lblsite.Text); cmd.Parameters.AddWithValue("@CUSTOMER_CODE", drpCustomerCode.SelectedItem.Value); cmd.Parameters.AddWithValue("@INVOICE_NO", txtInvoiceNo.Text); //cmd.Parameters.AddWithValue("@SO_NO", drpSONumber.SelectedItem.Value); cmd.Parameters.AddWithValue("@SO_NO", sono); cmd.Parameters.AddWithValue("@INVOIC_DATE", txtInvoiceDate.Text); cmd.Parameters.AddWithValue("@SO_DATE", txtSODate.Text); cmd.Parameters.AddWithValue("@CUSTGROUP_CODE", drpCustomerGroup.SelectedItem.Value); cmd.Parameters.AddWithValue("@LOADSHEET_NO", txtLoadSheetNumber.Text); cmd.Parameters.AddWithValue("@LOADSHEET_DATE", txtLoadsheetDate.Text); cmd.Parameters.AddWithValue("@TRANSPORTER_CODE", txtTransporterName.Text); cmd.Parameters.AddWithValue("@VEHICAL_NO", txtVehicleNo.Text); cmd.Parameters.AddWithValue("@DRIVER_CODE", txtDriverName.Text); cmd.Parameters.AddWithValue("@DRIVER_MOBILENO", txtDriverContact.Text); cmd.Parameters.AddWithValue("@status", "INSERT"); cmd.Parameters.AddWithValue("@TranType", 1); cmd.Parameters.AddWithValue("@NUMSEQ", NUMSEQ); cmd.Parameters.AddWithValue("@Remark", txtRemark.Text); decimal TDValue = 0; if (txtTDValue.Text == string.Empty) { TDValue = 0; txtTDValue.Text = "0"; } else { TDValue = Global.ConvertToDecimal(txtTDValue.Text); } cmd.Parameters.AddWithValue("@TDValue", TDValue); /* ---------- GST Implementation Start -----------*/ cmd.Parameters.AddWithValue("@DISTGSTINNO", Session["SITEGSTINNO"]); if (Session["SITEGSTINREGDATE"] != null && Session["SITEGSTINREGDATE"].ToString().Trim().Length > 0 && Convert.ToDateTime(Session["SITEGSTINREGDATE"]).Year != 1900) { cmd.Parameters.AddWithValue("@DISTGSTINREGDATE", Convert.ToDateTime(Session["SITEGSTINREGDATE"].ToString())); } cmd.Parameters.AddWithValue("@DISTCOMPOSITIONSCHEME", Convert.ToInt32(Session["SITECOMPOSITIONSCHEME"].ToString())); cmd.Parameters.AddWithValue("@CUSTGSTINNO", txtGSTtin.Text); if (txtGSTtinRegistration.Text != null && txtGSTtinRegistration.Text.Trim().Length > 0 && Convert.ToDateTime(txtGSTtinRegistration.Text).Year != 1900) { cmd.Parameters.AddWithValue("@CUSTGSTINREGDATE", Convert.ToDateTime(txtGSTtinRegistration.Text)); } cmd.Parameters.AddWithValue("@CUSTCOMPOSITIONSCHEME", (chkCompositionScheme.Checked == true ? 1 : 0)); cmd.Parameters.AddWithValue("@BILLTOADDRESS", txtAddress.Text); cmd.Parameters.AddWithValue("@SHIPTOADDRESS", ddlShipToAddress.SelectedValue.ToString()); cmd.Parameters.AddWithValue("@BILLTOSTATE", txtBillToState.Text); /* ---------- GST Implementation End -----------*/ //========Save Line================ int i = 0; decimal totamt = 0; //===================New=============== cmd1 = new SqlCommand("ACX_Insert_SaleInvoiceLine"); cmd1.Connection = conn; cmd1.Transaction = transaction; cmd1.CommandTimeout = 3600; cmd1.CommandType = CommandType.StoredProcedure; int count = gvDetails.Rows.Count; foreach (GridViewRow gv in gvDetails.Rows) { i = i + 1; HiddenField Tproduct = (HiddenField)gv.FindControl("HiddenField2"); Label Amt = (Label)gv.FindControl("Amount"); //totamt = totamt + Convert.ToDecimal(Amt.Text); TextBox box = (TextBox)gv.FindControl("txtBox"); if (box.Text.Trim().Length == 0) { box.Text = "0"; } Label ltr = (Label)gv.FindControl("ltr"); if (ltr.Text.Trim().Length == 0) { ltr.Text = "0"; } Label mrp = (Label)gv.FindControl("MRP"); if (mrp.Text.Trim().Length == 0) { mrp.Text = "0"; } TextBox rate = (TextBox)gv.FindControl("txtRate"); if (rate.Text.Trim().Length == 0) { rate.Text = "0"; } Label taxvalue = (Label)gv.FindControl("TaxValue"); if (taxvalue.Text.Trim().Length == 0) { taxvalue.Text = "0"; } Label taxper = (Label)gv.FindControl("Tax"); if (taxper.Text.Trim().Length == 0) { taxper.Text = "0"; } Label AddtaxPer = (Label)gv.FindControl("AddTax"); if (AddtaxPer.Text.Trim().Length == 0) { AddtaxPer.Text = "0"; } Label AddTaxValue = (Label)gv.FindControl("AddTaxValue"); if (AddTaxValue.Text.Trim().Length == 0) { AddTaxValue.Text = "0"; } //if (AddTaxValue.Text.Trim().Length == 0) { AddTaxValue.Text = "0"; } //if (Global.ConvertToDecimal(txtTDValue.Text) > 0) //{ // taxvalue = (Label)gv.FindControl("VatAfterPE"); // if (taxvalue.Text.Trim().Length == 0) { taxvalue.Text = "0"; } //} //else //{ //taxvalue = (Label)gv.FindControl("TaxValue"); //if (taxvalue.Text.Trim().Length == 0) { taxvalue.Text = "0"; } //} Label DiscVal = (Label)gv.FindControl("DiscValue"); if (DiscVal.Text.Trim().Length == 0) { DiscVal.Text = "0"; } Label Disc = (Label)gv.FindControl("Disc"); if (Disc.Text.Trim().Length == 0) { Disc.Text = "0"; } Label SchemeCode = (Label)gv.FindControl("lblScheme"); HiddenField hDT = (HiddenField)gv.FindControl("hDiscType"); HiddenField hCalculationBase = (HiddenField)gv.FindControl("hDiscCalculationType"); HiddenField hClaimDiscAmt = (HiddenField)gv.FindControl("hClaimDiscAmt"); HiddenField hTax1 = (HiddenField)gv.FindControl("hTax1"); HiddenField hTax2 = (HiddenField)gv.FindControl("hTax2"); HiddenField hTax1component = (HiddenField)gv.FindControl("hTax1component"); HiddenField hTax2component = (HiddenField)gv.FindControl("hTax2component"); //TextBox SDiscPer = (TextBox)gvDetails.Rows[i].FindControl("SecDisc"); TextBox SDiscVal = (TextBox)gv.FindControl("SecDiscValue"); if (SDiscVal.Text.Trim().Length == 0) { SDiscVal.Text = "0"; } Label lblTD = (Label)gv.FindControl("TD"); if (lblTD.Text.Trim().Length == 0) { lblTD.Text = "0"; } Label lblPE = (Label)gv.FindControl("PE"); if (lblPE.Text.Trim().Length == 0) { lblPE.Text = "0"; } Label lblTotal = (Label)gv.FindControl("Total"); if (lblTotal.Text.Trim().Length == 0) { lblTotal.Text = "0"; } totamt = totamt + Global.ConvertToDecimal(lblTotal.Text); HiddenField hdnTaxableammount = (HiddenField)gv.FindControl("hdnTaxableAmount"); HiddenField hdnBasePrice = (HiddenField)gv.FindControl("hdnBasePrice"); TextBox txtBoxQtyGrid = (TextBox)gv.FindControl("txtBoxQtyGrid"); if (txtBoxQtyGrid.Text.Trim().Length == 0) { txtBoxQtyGrid.Text = "0"; } TextBox txtPcsQtyGrid = (TextBox)gv.FindControl("txtPcsQtyGrid"); if (txtPcsQtyGrid.Text.Trim().Length == 0) { txtPcsQtyGrid.Text = "0"; } Label txtBoxPcs = (Label)gv.FindControl("txtBoxPcs"); if (txtBoxPcs.Text.Trim().Length == 0) { txtBoxPcs.Text = "0"; } Label lblHSNCODE = (Label)gv.FindControl("lblHSNCODE"); Label lblTAXCOMPONENT = (Label)gv.FindControl("lblTAXCOMPONENT"); Label lblADDTAXCOMPONENT = (Label)gv.FindControl("lblADDTAXCOMPONENT"); Label lblSchemeDiscPer = (Label)gv.FindControl("lblSchemeDiscPer"); if (lblSchemeDiscPer.Text.Trim().Length == 0) { lblSchemeDiscPer.Text = "0"; } Label lblSchemeDiscVal = (Label)gv.FindControl("lblSchemeDiscVal"); if (lblSchemeDiscVal.Text.Trim().Length == 0) { lblSchemeDiscVal.Text = "0"; } if (lblTD.Text == string.Empty) { lblTD.Text = "0.00"; } if (lblPE.Text == string.Empty) { lblPE.Text = "0.00"; } if (hDT.Value == "") { hDT.Value = "2"; } if (rate.Text == "") { rate.Text = "0"; } if (Disc.Text == "") { Disc.Text = "0"; } if (DiscVal.Text == "0") { DiscVal.Text = "0"; } decimal Tamount, Tbox, Tltr, Tmrp, Trate;//, decFinalAmount = 0; Tamount = Global.ConvertToDecimal(Amt.Text); Tbox = Global.ConvertToDecimal(box.Text); Tltr = Global.ConvertToDecimal(ltr.Text); Tmrp = Global.ConvertToDecimal(mrp.Text); Trate = Global.ConvertToDecimal(rate.Text); decimal LineAmount = 0; //taxvalue.Text = (taxvalue.Text.Trim().Length == 0 ? "0" : taxvalue.Text); //decimal taxamt = Global.ConvertToDecimal(taxvalue.Text); LineAmount = Trate * Tbox; //totamt = totamt + Tamount; if (Tbox > 0) { //cmd1.CommandText = ""; cmd1.Parameters.Clear(); cmd1.Parameters.AddWithValue("@status", "Insert"); cmd1.Parameters.AddWithValue("@SITEID", lblsite.Text); cmd1.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString()); cmd1.Parameters.AddWithValue("@RECID", ""); cmd1.Parameters.AddWithValue("@CUSTOMER_CODE", drpCustomerCode.SelectedItem.Value); cmd1.Parameters.AddWithValue("@INVOICE_NO", txtInvoiceNo.Text); cmd1.Parameters.AddWithValue("@LINE_NO", i); cmd1.Parameters.AddWithValue("@PRODUCT_CODE", Tproduct.Value); cmd1.Parameters.AddWithValue("@PRODUCTGROUP_CODE", ""); cmd1.Parameters.AddWithValue("@AMOUNT", Convert.ToDecimal(lblTotal.Text.Trim())); cmd1.Parameters.AddWithValue("@BOX", Convert.ToDecimal(Tbox.ToString().Trim())); cmd1.Parameters.AddWithValue("@CRATES", 0); cmd1.Parameters.AddWithValue("@LTR", Convert.ToDecimal(Tltr.ToString().Trim())); cmd1.Parameters.AddWithValue("@QUANTITY", 0); cmd1.Parameters.AddWithValue("@MRP", Convert.ToDecimal(Tmrp.ToString().Trim())); cmd1.Parameters.AddWithValue("@RATE", Convert.ToDecimal(Trate.ToString().Trim())); cmd1.Parameters.AddWithValue("@TAX_CODE", Convert.ToDecimal(taxper.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@TAX_AMOUNT", Convert.ToDecimal(taxvalue.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@ADDTAX_CODE", Convert.ToDecimal(AddtaxPer.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@ADDTAX_AMOUNT", Convert.ToDecimal(AddTaxValue.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@DISC_AMOUNT", Convert.ToDecimal(DiscVal.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@SEC_DISC_AMOUNT", Convert.ToDecimal(SDiscVal.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@TranType", 1); cmd1.Parameters.AddWithValue("@DiscType", hDT.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Disc", Convert.ToDecimal(Disc.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@SchemeCode", SchemeCode.Text.ToString().Trim()); //cmd1.Parameters.AddWithValue("@SchemeCode", ""); cmd1.Parameters.AddWithValue("@LINEAMOUNT", Convert.ToDecimal(LineAmount.ToString().Trim())); cmd1.Parameters.AddWithValue("@DiscCalculationBase", hCalculationBase.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@CLAIM_DISC_AMT", hClaimDiscAmt.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Tax1", hTax1.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Tax2", hTax2.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Tax1component", hTax1component.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Tax2component", hTax2component.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@TDValue", Convert.ToDecimal(lblTD.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@PEValue", Convert.ToDecimal(lblPE.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@BasePrice", Convert.ToDecimal(hdnBasePrice.Value.ToString().Trim())); cmd1.Parameters.AddWithValue("@BOXQty", Convert.ToDecimal(txtBoxQtyGrid.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@PcsQty", Convert.ToDecimal(txtPcsQtyGrid.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@BOXPcs", Convert.ToDecimal(txtBoxPcs.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@TaxableAmount", Math.Round(Convert.ToDecimal(hdnTaxableammount.Value),2)); /*-------- GST IMPLEMENTATION START --------*/ cmd1.Parameters.AddWithValue("@HSNCODE", lblHSNCODE.Text.ToString().Trim()); cmd1.Parameters.AddWithValue("@COMPOSITIONSCHEME", Convert.ToInt32(Session["SITECOMPOSITIONSCHEME"].ToString())); cmd1.Parameters.AddWithValue("@TAXCOMPONENT", lblTAXCOMPONENT.Text.ToString().Trim()); cmd1.Parameters.AddWithValue("@ADDTAXCOMPONENT", lblADDTAXCOMPONENT.Text.ToString().Trim()); cmd1.Parameters.AddWithValue("@DOCTYPE", 6); cmd1.Parameters.AddWithValue("@SchemeDiscPer", Convert.ToDecimal(lblSchemeDiscPer.Text.ToString().Trim())); cmd1.Parameters.AddWithValue("@SchemeDiscVal", Convert.ToDecimal(lblSchemeDiscVal.Text.ToString().Trim())); /*-------- GST IMPLEMENTATION END ---------*/ cmd1.ExecuteNonQuery(); } } //===============Update Transaction Table=============== cmd2 = new SqlCommand("ACX_Insert_InventTransTable"); //new SqlCommand(); cmd2.Connection = conn; cmd2.Transaction = transaction; cmd2.CommandTimeout = 3600; cmd2.CommandType = CommandType.StoredProcedure; //CommandType.Text; //==================Common Data-============== string st = Session["SiteCode"].ToString(); string Siteid = Session["SiteCode"].ToString(); string TransId = st.Substring(st.Length - 6) + System.DateTime.Now.ToString("yymmddhhmmss"); string DATAAREAID = Session["DATAAREAID"].ToString(); int TransType = 2;//1 for Slae invoice int DocumentType = 2; string DocumentNo = txtInvoiceNo.Text; string DocumentDate = txtInvoiceDate.Text; string uom = "BOX"; string Referencedocumentno = drpSONumber.SelectedItem.Text; string TransLocation = Session["TransLocation"].ToString(); int l = 0; //============Loop For LineItem========== for (int k = 0; k < gvDetails.Rows.Count; k++) { Label Product = (Label)gvDetails.Rows[k].Cells[2].FindControl("Product"); TextBox box = (TextBox)gvDetails.Rows[k].Cells[6].FindControl("txtBox"); string productNameCode = Product.Text; string[] str = productNameCode.Split('-'); string ProductCode = str[0].ToString(); string Qty = box.Text; decimal TransQty = Global.ConvertToDecimal(Qty); int REcid = k + 1; if (TransQty > 0) { cmd2.Parameters.Clear(); cmd2.Parameters.AddWithValue("@status", "Insert"); cmd2.Parameters.AddWithValue("@SITEID", lblsite.Text); cmd2.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString()); cmd2.Parameters.AddWithValue("@RECID", ""); cmd2.Parameters.AddWithValue("@TransId", TransId); cmd2.Parameters.AddWithValue("@TransType", TransType); cmd2.Parameters.AddWithValue("@DocumentType", DocumentType); cmd2.Parameters.AddWithValue("@DocumentNo", DocumentNo); cmd2.Parameters.AddWithValue("@DocumentDate", DocumentDate); cmd2.Parameters.AddWithValue("@ProductCode", ProductCode); cmd2.Parameters.AddWithValue("@TransQty", -TransQty); cmd2.Parameters.AddWithValue("@uom", uom); cmd2.Parameters.AddWithValue("@TransLocation", TransLocation); cmd2.Parameters.AddWithValue("@Referencedocumentno", Referencedocumentno); cmd2.Parameters.AddWithValue("@TransLineNo", l); cmd2.ExecuteNonQuery(); l += 1; } } //============Loop For Scheme LineItem========== foreach (GridViewRow gv in gvScheme.Rows) { if (((CheckBox)gv.FindControl("chkSelect")).Checked) { // i = i + 1; TextBox txtQtyToAvail = (TextBox)gv.FindControl("txtQty"); TextBox txtQtyToAvailPcs = (TextBox)gv.FindControl("txtQtyPcs"); txtQtyToAvail.Text = (txtQtyToAvail.Text.Trim().Length == 0 ? "0" : txtQtyToAvail.Text); txtQtyToAvailPcs.Text = (txtQtyToAvailPcs.Text.Trim().Length == 0 ? "0" : txtQtyToAvailPcs.Text); //TextBox txtQtyToAvail = (TextBox)gv.FindControl("txtQty"); string Sproduct = gv.Cells[4].Text; decimal packSize = 1, boxqty = 0, pcsQty = 0; decimal billQty = 0; string boxPcs = ""; using (DataTable dtFreeItem = baseObj.GetData("Select Cast(ISNULL(Product_PackSize,1) as int) AS Product_PackSize From AX.InventTable Where ItemId='" + gv.Cells[4].Text.ToString() + "'")) { if (dtFreeItem.Rows.Count > 0) { string strPack = dtFreeItem.Rows[0]["Product_PackSize"].ToString(); packSize = Global.ConvertToDecimal(strPack); } } if (Convert.ToInt16(txtQtyToAvailPcs.Text) > 0) { pcsQty = Convert.ToInt32(txtQtyToAvailPcs.Text); } else { pcsQty = 0; } // boxqty = (pcsQty >= packSize ? Convert.ToInt32(pcsQty / packSize) : 0); boxqty = (pcsQty >= packSize ? Convert.ToInt32(Math.Floor(pcsQty / packSize)) : 0); pcsQty = Convert.ToInt32(txtQtyToAvailPcs.Text) - (boxqty * packSize); boxqty = boxqty + Convert.ToInt32(txtQtyToAvail.Text); billQty = Math.Round((boxqty + (pcsQty / packSize)), 2);// Math.Round(Convert.ToDecimal((boxqty + (pcsQty / packSize))), 2); boxPcs = boxqty.ToString() + "." + (pcsQty.ToString().Length == 1 ? "0" : "") + pcsQty.ToString(); decimal TransQty = billQty; // totamt = 0; { cmd2.Parameters.Clear(); cmd2.Parameters.AddWithValue("@status", "Insert"); cmd2.Parameters.AddWithValue("@SITEID", lblsite.Text); cmd2.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString()); cmd2.Parameters.AddWithValue("@RECID", ""); cmd2.Parameters.AddWithValue("@TransId", TransId); cmd2.Parameters.AddWithValue("@TransType", TransType); cmd2.Parameters.AddWithValue("@DocumentType", DocumentType); cmd2.Parameters.AddWithValue("@DocumentNo", DocumentNo); cmd2.Parameters.AddWithValue("@DocumentDate", DocumentDate); cmd2.Parameters.AddWithValue("@ProductCode", Sproduct); cmd2.Parameters.AddWithValue("@TransQty", -TransQty); cmd2.Parameters.AddWithValue("@uom", uom); cmd2.Parameters.AddWithValue("@TransLocation", TransLocation); cmd2.Parameters.AddWithValue("@Referencedocumentno", Referencedocumentno); cmd2.Parameters.AddWithValue("@TransLineNo", l); cmd2.ExecuteNonQuery(); l += 1; } } } //=================================================== // Insert For Scheme Line i = gvDetails.Rows.Count; foreach (GridViewRow gv in gvScheme.Rows) { if (((CheckBox)gv.FindControl("chkSelect")).Checked) { i = i + 1; TextBox txtQtyToAvail = (TextBox)gv.FindControl("txtQty"); TextBox txtQtyToAvailPcs = (TextBox)gv.FindControl("txtQtyPcs"); txtQtyToAvail.Text = (txtQtyToAvail.Text.Trim().Length == 0 ? "0" : txtQtyToAvail.Text); txtQtyToAvailPcs.Text = (txtQtyToAvailPcs.Text.Trim().Length == 0 ? "0" : txtQtyToAvailPcs.Text); HiddenField pr = (HiddenField)gv.Cells[2].FindControl("HiddenField2"); HiddenField hScTax1component = (HiddenField)gv.Cells[2].FindControl("hScTax1component"); HiddenField hScTax2component = (HiddenField)gv.Cells[2].FindControl("hScTax2component"); HiddenField hScTax1 = (HiddenField)gv.Cells[2].FindControl("hScTax1"); HiddenField hScTax2 = (HiddenField)gv.Cells[2].FindControl("hScTax2"); decimal decQtyToAvail = Global.ConvertToDecimal(txtQtyToAvail.Text); // totamt = 0; { #region For Box Pcs Conv decimal packSize = 1, boxqty = 0, pcsQty = 0; decimal billQty = 0; string boxPcs = ""; using (DataTable dtFreeItem = baseObj.GetData("Select Cast(ISNULL(Product_PackSize,1) as int) AS Product_PackSize From AX.InventTable Where ItemId='" + gv.Cells[4].Text.ToString() + "'")) { if (dtFreeItem.Rows.Count > 0) { string strPack = dtFreeItem.Rows[0]["Product_PackSize"].ToString(); packSize = Global.ConvertToDecimal(strPack); } } if (Convert.ToInt16(txtQtyToAvailPcs.Text) > 0) { pcsQty = Convert.ToInt32(txtQtyToAvailPcs.Text); } else { pcsQty = 0; } //boxqty = (pcsQty >= packSize ? Convert.ToInt32(pcsQty / packSize) : 0); boxqty = (pcsQty >= packSize ? Convert.ToInt32(Math.Floor(pcsQty / packSize)) : 0); pcsQty = Convert.ToInt32(txtQtyToAvailPcs.Text) - (boxqty * packSize); boxqty = boxqty + Convert.ToInt32(txtQtyToAvail.Text); billQty = Math.Round((boxqty + (pcsQty / packSize)), 4);// Math.Round(Convert.ToDecimal((boxqty + (pcsQty / packSize))), 2); boxPcs = boxqty.ToString() + "." + (pcsQty.ToString().Length == 1 ? "0" : "") + pcsQty.ToString(); string[] calValue = baseObj.CalculatePrice1(gv.Cells[4].Text, drpCustomerCode.SelectedItem.Value, billQty, "Box"); string strLtr = string.Empty; if (calValue[1] != null) { strLtr = calValue[1].ToString(); } string strUOM = string.Empty; if (calValue[4] != null) { strUOM = calValue[4].ToString(); } #endregion //totamt = totamt + Global.ConvertToDecimal(lblTotal.Text); if (billQty > 0) { cmd1.Parameters.Clear(); cmd1.Parameters.AddWithValue("@status", "Insert"); cmd1.Parameters.AddWithValue("@SITEID", lblsite.Text); cmd1.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString()); cmd1.Parameters.AddWithValue("@RECID", ""); cmd1.Parameters.AddWithValue("@CUSTOMER_CODE", drpCustomerCode.SelectedItem.Value); cmd1.Parameters.AddWithValue("@INVOICE_NO", txtInvoiceNo.Text); cmd1.Parameters.AddWithValue("@LINE_NO", i); cmd1.Parameters.AddWithValue("@PRODUCT_CODE", gv.Cells[4].Text); cmd1.Parameters.AddWithValue("@PRODUCTGROUP_CODE", ""); cmd1.Parameters.AddWithValue("@AMOUNT", Convert.ToDecimal(gv.Cells[24].Text)); cmd1.Parameters.AddWithValue("@BOX", billQty); cmd1.Parameters.AddWithValue("@BOXPcs", boxPcs); cmd1.Parameters.AddWithValue("@BOXQty", txtQtyToAvail.Text); cmd1.Parameters.AddWithValue("@PcsQty", txtQtyToAvailPcs.Text); cmd1.Parameters.AddWithValue("@BasePrice", Convert.ToDecimal(gv.Cells[15].Text)); cmd1.Parameters.AddWithValue("@TaxableAmount", Convert.ToDecimal(gv.Cells[19].Text)); //================================ cmd1.Parameters.AddWithValue("@CRATES", 0); cmd1.Parameters.AddWithValue("@LTR", strLtr); cmd1.Parameters.AddWithValue("@QUANTITY", 0); cmd1.Parameters.AddWithValue("@MRP", 0); cmd1.Parameters.AddWithValue("@RATE", Convert.ToDecimal(gv.Cells[15].Text)); cmd1.Parameters.AddWithValue("@TAX_CODE", Convert.ToDecimal(gv.Cells[20].Text)); cmd1.Parameters.AddWithValue("@TAX_AMOUNT", Convert.ToDecimal(gv.Cells[21].Text)); cmd1.Parameters.AddWithValue("@ADDTAX_CODE", Convert.ToDecimal(gv.Cells[22].Text)); cmd1.Parameters.AddWithValue("@ADDTAX_AMOUNT", Convert.ToDecimal(gv.Cells[23].Text)); cmd1.Parameters.AddWithValue("@DISC_AMOUNT", 0); cmd1.Parameters.AddWithValue("@SEC_DISC_AMOUNT", 0); cmd1.Parameters.AddWithValue("@TranType", 1); cmd1.Parameters.AddWithValue("@DiscType", 2); cmd1.Parameters.AddWithValue("@Disc", 0); cmd1.Parameters.AddWithValue("@SchemeCode", gv.Cells[1].Text); cmd1.Parameters.AddWithValue("@LINEAMOUNT", Convert.ToDecimal(gv.Cells[16].Text)); cmd1.Parameters.AddWithValue("@DiscCalculationBase", 2); cmd1.Parameters.AddWithValue("@TDValue", 0); cmd1.Parameters.AddWithValue("@PEValue", 0); cmd1.Parameters.AddWithValue("@HSNCODE", gv.Cells[25].Text); cmd1.Parameters.AddWithValue("@COMPOSITIONSCHEME", Convert.ToInt32(Session["SITECOMPOSITIONSCHEME"].ToString())); cmd1.Parameters.AddWithValue("@TAXCOMPONENT", gv.Cells[26].Text); cmd1.Parameters.AddWithValue("@ADDTAXCOMPONENT", gv.Cells[27].Text); cmd1.Parameters.AddWithValue("@DOCTYPE", 6); cmd1.Parameters.AddWithValue("@SchemeDiscPer", Convert.ToDecimal(gv.Cells[17].Text)); cmd1.Parameters.AddWithValue("@SchemeDiscVal", Convert.ToDecimal(gv.Cells[18].Text)); cmd1.Parameters.AddWithValue("@Tax1", hScTax1.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Tax2", hScTax2.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Tax1component", hScTax1component.Value.ToString().Trim()); cmd1.Parameters.AddWithValue("@Tax2component", hScTax2component.Value.ToString().Trim()); cmd1.ExecuteNonQuery(); totamt = totamt + Convert.ToDecimal(gv.Cells[24].Text); } } } } //==============Remaining Part Of Header-=============== cmd.Parameters.AddWithValue("@INVOICE_VALUE", totamt); cmd.ExecuteNonQuery(); //============Commit All Data================ transaction.Commit(); Session["SO_NOList"] = null; dtLineItems = null; Session["InvLineItem"] = null; Session["InvSchemeLineItem"] = null; } catch (Exception ex) { transaction.Rollback(); lblMessage.Text = ex.Message.ToString(); string message = "alert('" + ex.Message.ToString() + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); txtInvoiceNo.Text = ""; ErrorSignal.FromCurrentContext().Raise(ex); } finally { conn.Close(); } } public void UpdateTransTable() { try { CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); //==================Common Data-============== string st = Session["SiteCode"].ToString(); string Siteid = Session["SiteCode"].ToString(); string DATAAREAID = Session["DATAAREAID"].ToString(); int TransType = 2;//1 for Slae invoice int DocumentType = 2; string DocumentNo = txtInvoiceNo.Text; string DocumentDate = txtInvoiceDate.Text; string uom = "BOX"; string Referencedocumentno = drpSONumber.SelectedItem.Text; string TransLocation = Session["TransLocation"].ToString(); //============Loop For LineItem========== for (int i = 0; i < gvDetails.Rows.Count; i++) { Label Product = (Label)gvDetails.Rows[i].Cells[2].FindControl("Product"); TextBox box = (TextBox)gvDetails.Rows[i].Cells[6].FindControl("txtBox"); string TransId = st.Substring(st.Length - 6) + System.DateTime.Now.ToString("yymmddhhmmss"); string productNameCode = Product.Text; string[] str = productNameCode.Split('-'); string ProductCode = str[0].ToString(); string Qty = box.Text; decimal TransQty = Global.ConvertToDecimal(Qty); int REcid = i + 1; if (TransQty > 0) { string query = " Insert Into ax.acxinventTrans " + "([TransId],[SiteCode],[DATAAREAID],[RECID],[InventTransDate],[TransType],[DocumentType]," + "[DocumentNo],[DocumentDate],[ProductCode],[TransQty],[TransUOM],[TransLocation],[Referencedocumentno])" + " Values ('" + TransId + "','" + Siteid + "','" + DATAAREAID + "'," + REcid + ",getdate()," + TransType + "," + DocumentType + ",'" + DocumentNo + "'," + " '" + DocumentDate + "','" + ProductCode + "'," + -TransQty + ",'" + uom + "','" + TransLocation + "','" + Referencedocumentno + "')"; obj.ExecuteCommand(query); } } } catch(Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } } public void ClearAll() { txtViewTotalBox.Text = ""; txtViewTotalPcs.Text = ""; txtBoxPcs.Text = ""; //gvDetails.Columns[11].Visible = true; drpCustomerCode.Items.Clear(); drpCustomerCode.Items.Clear(); txtTIN.Text = ""; txtAddress.Text = ""; txtMobileNO.Text = ""; txtLoadSheetNumber.Text = ""; txtLoadsheetDate.Text = ""; drpSONumber.Items.Clear(); txtSODate.Text = ""; txtTransporterName.Text = ""; txtDriverContact.Text = ""; txtDriverName.Text = ""; txtVehicleNo.Text = ""; txtInvoiceNo.Text = ""; txtInvoiceDate.Text = ""; gvDetails.DataSource = null; gvDetails.DataBind(); gvScheme.DataSource = null; gvScheme.DataBind(); txtSecDiscPer.Text = "0.00"; txtSecDiscValue.Text = "0.00"; txtRemark.Text = string.Empty; txtLtr.Text = string.Empty; txtPrice.Text = string.Empty; txtValue.Text = string.Empty; txtStockQty.Text = string.Empty; txtPack.Text = string.Empty; txtMRP.Text = string.Empty; txtViewTotalBox.Text = ""; txtViewTotalPcs.Text = ""; } protected void lnkbtn_Click(object sender, EventArgs e) { } protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e) { } protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e) { } protected void btnBack_Click(object sender, EventArgs e) { //Cache.Remove("SO_NO"); Session["SO_NOList"] = null; Response.Redirect("~/frmInvoicePrepration.aspx"); } private bool Validation() { bool returnvalue = true; try { // Check For Valid Delivery Date if (txtAddress.Text.Trim().Length == 0) { string message = "alert('Customers Bill To Address Required !!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; return returnvalue; } if (txtBillToState.Text.Trim().Length == 0) { string message = "alert('Customer Bill To State Required !!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; return returnvalue; } if (ddlShipToAddress.SelectedValue == null || ddlShipToAddress.SelectedValue.ToString().Trim().Length == 0) { string message = "alert('Customers Ship To Address Required !!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; return returnvalue; } if (drpCustomerCode.Text == "") { //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide Customer Name !');", true); string message = "alert('Please Provide Customer Name !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); drpCustomerGroup.Focus(); returnvalue = false; return returnvalue; } else if (drpCustomerGroup.Text == "") { // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide Customer Group !');", true); string message = "alert('Please Provide Customer Group !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); drpCustomerGroup.Focus(); returnvalue = false; return returnvalue; } else if (drpSONumber.Text == "") { //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide Sale Order Number !');", true); string message = "alert('Please Provide Sale Order Number !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); drpSONumber.Focus(); returnvalue = false; return returnvalue; } else if (txtInvoiceDate.Text == "") { //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide Invoice Date !');", true); txtInvoiceDate.Text = string.Format("{0:dd/MMM/yyyy }", DateTime.Today); //string message = "alert('Please Provide Invoice Date !');"; //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true); //txtInvoiceDate.Focus(); //returnvalue = false; //return returnvalue; } //=============================== CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); DataTable dt = new DataTable(); //=============So checking its already in the invoice table?======== if (Session["SO_NOList"] == null) { string message = "alert('Invoice_save session expired ,Please select Invoice No ...'); window.location.href='frmInvoicePrepration.aspx'; "; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } string sono = Session["SO_NOList"].ToString();// Cache["SO_NO"].ToString(); string query1 = "select * from ax.ACXSALEINVOICEHEADER " + "where [Siteid]='" + lblsite.Text + "' and SO_NO in (select id from [dbo].[CommaDelimitedToTable]('" + sono + "' ,',')) and invoice_no not in (select so_no from ax.ACXSALEINVOICEHEADER B where [Siteid]='" + lblsite.Text + "' and trantype=2)"; dt = new DataTable(); dt = obj.GetData(query1); if (dt.Rows.Count > 0) { string message = "alert('Already Created Invoice No: " + txtInvoiceNo.Text + " againts the SO NO: " + drpSONumber.SelectedItem.Text + " !')"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; return returnvalue; } //============Check Stock Item Line By Line====== dt = new DataTable(); int valrow = 0; decimal totalInvoiceValue = 0; Label lblTotal; for (int i = 0; i < gvDetails.Rows.Count; i++) { lblTotal = (Label)gvDetails.Rows[i].Cells[2].FindControl("Total"); totalInvoiceValue += Global.ConvertToDecimal(lblTotal.Text); Label Product = (Label)gvDetails.Rows[i].Cells[2].FindControl("Product"); string productNameCode = Product.Text; string[] str = productNameCode.Split('-'); string ProductCode = str[0].ToString(); TextBox box = (TextBox)gvDetails.Rows[i].Cells[6].FindControl("txtBox"); string Qty = box.Text; decimal TransQty = Global.ConvertToDecimal(Qty); if (TransQty > 0) { valrow = valrow + 1; } string query = "select ProductCode from ax.acxinventTrans group by sitecode,translocation,ProductCode " + " Having sitecode='" + Session["SiteCode"].ToString() + "' and translocation='" + Session["TransLocation"].ToString() + "' and ProductCode='" + ProductCode + "' and sum(TransQty)>=" + TransQty + ""; dt = obj.GetData(query); if (Convert.ToDecimal(Qty)>0) { if (dt.Rows.Count <= 0) { string message = "alert('Product :" + productNameCode + " is out of stock !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; return returnvalue; } } } if (totalInvoiceValue <= 0) { string message = "alert('Invoice value should not be less than zero!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; return returnvalue; } if (valrow <= 0) { string message = "alert('Please enter valid data !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; return returnvalue; } return returnvalue; } catch (Exception ex) { string message = "alert('" + ex.Message + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); returnvalue = false; ErrorSignal.FromCurrentContext().Raise(ex); return returnvalue; } } protected void txtTransporterName_TextChanged(object sender, EventArgs e) { txtDriverName.Focus(); } protected void txtDriverName_TextChanged(object sender, EventArgs e) { txtDriverContact.Focus(); } protected void txtDriverContact_TextChanged(object sender, EventArgs e) { txtVehicleNo.Focus(); } public void BindSchemeGrid() { DataTable dt = GetDatafromSP(@"ACX_SCHEME"); if (dt != null) { foreach (DataRow row in dt.Rows) { DataTable dtscheme = new DataTable(); dtscheme = baseObj.GetData("EXEC USP_ACX_GetSalesLineCalcGST '" + row["Free Item Code"].ToString() + "','" + drpCustomerCode.SelectedValue.ToString() + "','" + Session["SiteCode"].ToString() + "',1," + Convert.ToDecimal(row["Rate"].ToString()) + ",'" + Session["SITELOCATION"].ToString() + "','" + drpCustomerGroup.SelectedValue.ToString() + "','" + Session["DATAAREAID"].ToString() + "'"); if (dtscheme.Rows.Count > 0) { dt.Columns["Tax1Per"].ReadOnly = false; dt.Columns["Tax2Per"].ReadOnly = false; dt.Columns["Tax1"].ReadOnly = false; dt.Columns["Tax2"].ReadOnly = false; dt.Columns["Tax1Component"].ReadOnly = false; dt.Columns["Tax2Component"].ReadOnly = false; dt.Columns["Tax2Component"].MaxLength = 20; dt.Columns["Tax1Component"].MaxLength = 20; if (dtscheme.Rows[0]["RETMSG"].ToString().IndexOf("TRUE") >= 0) { row["Tax1Per"] = dtscheme.Rows[0]["TAX_PER"]; row["Tax2Per"] = dtscheme.Rows[0]["ADDTAX_PER"]; row["Tax1"] = dtscheme.Rows[0]["Tax1"]; row["Tax2"] = dtscheme.Rows[0]["Tax2"]; row["Tax1Component"] = dtscheme.Rows[0]["TAX1COMPONENT"]; row["Tax2Component"] = dtscheme.Rows[0]["TAX2COMPONENT"]; dt.AcceptChanges(); } } } } gvScheme.DataSource = dt; gvScheme.DataBind(); //Session["InvSchemeLineItem"] = null; //AddColumnInSchemeDataTable(); //DataTable dt = GetDatafromSP(@"ACX_SCHEME"); //gvScheme.DataSource = dt; //gvScheme.DataBind(); //Session["InvSchemeLineItem"] = dt; } public DataTable GetDatafromSP(string SPName) { conn = baseObj.GetConnection(); try { string ItemGroup = string.Empty; string ItemCode = string.Empty; foreach (GridViewRow row in gvDetails.Rows) { Label lblItem = (Label)row.Cells[2].FindControl("Product"); string[] arritem = lblItem.Text.Split('-'); string strItemCode = arritem[0].ToString().Trim(); if (row.RowIndex == 0) { ItemCode = "" + strItemCode + ""; } else { ItemCode += "," + strItemCode + ""; } } cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandTimeout = 3600; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = SPName; cmd.Parameters.AddWithValue("@PLACESITE", Session["SiteCode"].ToString()); cmd.Parameters.AddWithValue("@PLACESTATE", Session["SCHSTATE"].ToString()); cmd.Parameters.AddWithValue("@PLACEALL", ""); cmd.Parameters.AddWithValue("@CUSCODECUS", drpCustomerCode.SelectedValue.ToString()); cmd.Parameters.AddWithValue("@CUSCODEGROUP", drpCustomerGroup.SelectedValue.ToString()); cmd.Parameters.AddWithValue("@CUSCODEALL", ""); cmd.Parameters.AddWithValue("@ITEMITEM", ItemCode); cmd.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString()); //cmd.Parameters.AddWithValue("@ITEMGROUP",DDLProductGroup.SelectedValue.ToString()); cmd.Parameters.AddWithValue("@ITEMALL", ""); DataTable dt = new DataTable(); dt.Load(cmd.ExecuteReader()); if (dt.Rows.Count > 0) { dt.Columns.Add("TotalFreeQty", typeof(System.Int16)); dt.Columns.Add("TotalFreeQtyPCS", typeof(System.Int16)); DataTable dt1 = dt.Clone(); dt1.Clear(); Int16 TotalQtyofGroupItem = 0; Int16 TotalPCSQtyofGroupItem = 0; //decimal TotalQtyofGroupItem = 0; Int16 TotalQtyofItem = 0; Int16 TotalPCSQtyofItem = 0; //decimal TotalQtyofItem = 0; Int16 TotalMaxQtyofItem = 0; Int16 TotalMaxPCSQtyofItem = 0; //decimal TotalMaxQtyofItem = 0; decimal TotalValueofGroupItem = 0; decimal TotalValueofItem = 0; decimal TotalMaxValueofItem = 0; foreach (DataRow dr in dt.Rows) { #region Picking Scheme For Bill Qty if (dr["Scheme Type"].ToString() == "0") // For Qty { if (Convert.ToInt16(dr["MINIMUMQUANTITY"]) > 0) { TotalQtyofGroupItem = GetQtyofGroupItem(dr["Scheme Item group"].ToString(), "BOX"); TotalQtyofItem = GetQtyofItem(dr["Scheme Item group"].ToString(), "BOX"); TotalMaxQtyofItem = GetMaxQtyofItem("BOX"); #region Picking Scheme For Box Qty Free if (Convert.ToInt16(dr["FREEQTY"]) > 0) { if (dr["Scheme Item Type"].ToString() == "Group" && TotalQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITY"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITY"]))) * Convert.ToInt16(dr["FREEQTY"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "Item" && TotalQtyofItem >= Convert.ToInt16(dr["MINIMUMQUANTITY"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofItem / Convert.ToInt16(dr["MINIMUMQUANTITY"]))) * Convert.ToInt16(dr["FREEQTY"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "All" && TotalQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITY"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITY"]))) * Convert.ToInt16(dr["FREEQTY"])); dt1.ImportRow(dr); } } #endregion #region Picking Scheme For PCS Qty Free if (Convert.ToInt16(dr["FREEQTYPCS"]) > 0) { if (dr["Scheme Item Type"].ToString() == "Group" && TotalQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITY"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITY"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "Item" && TotalQtyofItem >= Convert.ToInt16(dr["MINIMUMQUANTITY"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofItem / Convert.ToInt16(dr["MINIMUMQUANTITY"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "All" && TotalQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITY"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITY"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } } #endregion } if (Convert.ToInt16(dr["MINIMUMQUANTITYPCS"]) > 0) { TotalPCSQtyofGroupItem = GetQtyofGroupItem(dr["Scheme Item group"].ToString(), "PCS"); TotalPCSQtyofItem = GetQtyofItem(dr["Scheme Item group"].ToString(), "PCS"); TotalMaxPCSQtyofItem = GetMaxQtyofItem("PCS"); #region Picking Scheme For Box Free Qty if (Convert.ToInt16(dr["FREEQTY"]) > 0) { if (dr["Scheme Item Type"].ToString() == "Group" && TotalPCSQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITYPCS"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(dr["FREEQTY"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "Item" && TotalPCSQtyofItem >= Convert.ToInt16(dr["MINIMUMQUANTITYPCS"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofItem / Convert.ToInt16(dr["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(dr["FREEQTY"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "All" && TotalPCSQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITYPCS"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(dr["FREEQTY"])); dt1.ImportRow(dr); } } #endregion #region Picking Scheme For PCS Free Qty if (Convert.ToInt16(dr["FREEQTYPCS"]) > 0) { if (dr["Scheme Item Type"].ToString() == "Group" && TotalPCSQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITYPCS"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "Item" && TotalPCSQtyofItem >= Convert.ToInt16(dr["MINIMUMQUANTITYPCS"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofItem / Convert.ToInt16(dr["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "All" && TotalPCSQtyofGroupItem >= Convert.ToInt16(dr["MINIMUMQUANTITYPCS"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(dr["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } } #endregion } } #endregion #region Picking Scheme For Value if (dr["Scheme Type"].ToString() == "1") // For Value { TotalValueofGroupItem = GetValueofGroupItem(dr["Scheme Item group"].ToString()); TotalValueofItem = GetValueofItem(dr["Scheme Item group"].ToString()); TotalMaxValueofItem = GetMaxValueofItem(); if (Convert.ToDecimal(dr["MINIMUMVALUE"]) > 0) { if (Convert.ToInt16(dr["FREEQTY"]) > 0) { if (dr["Scheme Item Type"].ToString() == "Group" && TotalValueofGroupItem >= Convert.ToDecimal(dr["MINIMUMVALUE"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToDecimal(dr["MINIMUMVALUE"]))) * Convert.ToInt16(dr["FREEQTY"])); //dr["FREEQTY"] = dr["TotalFreeQty"]; dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "Item" && TotalValueofItem >= Convert.ToDecimal(dr["MINIMUMVALUE"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofItem / Convert.ToDecimal(dr["MINIMUMVALUE"]))) * Convert.ToInt16(dr["FREEQTY"])); //dr["FREEQTY"] = dr["TotalFreeQty"]; dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "All" && TotalValueofGroupItem >= Convert.ToDecimal(dr["MINIMUMVALUE"])) { dr["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToDecimal(dr["MINIMUMVALUE"]))) * Convert.ToInt16(dr["FREEQTY"])); //dr["FREEQTY"] = dr["TotalFreeQty"]; dt1.ImportRow(dr); } } if (Convert.ToInt16(dr["FREEQTYPCS"]) > 0) { if (dr["Scheme Item Type"].ToString() == "Group" && TotalValueofGroupItem >= Convert.ToDecimal(dr["MINIMUMVALUE"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToDecimal(dr["MINIMUMVALUE"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "Item" && TotalValueofItem >= Convert.ToDecimal(dr["MINIMUMVALUE"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofItem / Convert.ToDecimal(dr["MINIMUMVALUE"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } if (dr["Scheme Item Type"].ToString() == "All" && TotalValueofGroupItem >= Convert.ToDecimal(dr["MINIMUMVALUE"])) { dr["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToDecimal(dr["MINIMUMVALUE"]))) * Convert.ToInt16(dr["FREEQTYPCS"])); dt1.ImportRow(dr); } } } } #endregion } DataTable dt3 = dt1.Clone(); #region For Qty DataView view = new DataView(dt1); view.RowFilter = "[Scheme Type]=0"; DataTable distinctTable = (DataTable)view.ToTable(true, "SCHEMECODE", "Scheme Item Type", "MINIMUMQUANTITY"); DataView dvSort = new DataView(distinctTable); dvSort.Sort = "SCHEMECODE ASC, MINIMUMQUANTITY DESC"; DataView Dv1 = null; int intCalRemFreeQty = 0; Int16 RemainingQty = 0; string schemeCode = string.Empty; foreach (DataRowView drv in dvSort) { if (schemeCode != drv.Row["SCHEMECODE"].ToString()) { intCalRemFreeQty = 0; schemeCode = drv.Row["SCHEMECODE"].ToString(); } if (intCalRemFreeQty == 0) { // Qty Scheme Filter if (Convert.ToInt16(drv.Row["MINIMUMQUANTITY"]) > 0) { #region Scheme Free Lines BOX Free Qty Dv1 = new DataView(dt1); Dv1.RowFilter = "SCHEMECODE='" + drv.Row["SCHEMECODE"] + "' and [Scheme Item Type]='" + drv.Row["Scheme Item Type"] + "' and MINIMUMQUANTITY='" + drv.Row["MINIMUMQUANTITY"] + "' AND FREEQTY>0"; foreach (DataRowView drv2 in Dv1) { TotalQtyofGroupItem = GetQtyofGroupItem(drv2["Scheme Item group"].ToString(), "BOX"); TotalQtyofItem = GetQtyofItem(drv2["Scheme Item group"].ToString(), "BOX"); TotalMaxQtyofItem = GetMaxQtyofItem("BOX"); if (drv["Scheme Item Type"].ToString() == "Group" && TotalQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITY"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITY"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); // RemainingQty = Convert.ToInt16(TotalQtyofGroupItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "Item" && TotalQtyofItem >= Convert.ToInt16(drv["MINIMUMQUANTITY"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofItem / Convert.ToInt16(drv2["MINIMUMQUANTITY"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); // RemainingQty = Convert.ToInt16(TotalQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "All" && TotalQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITY"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITY"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); // RemainingQty = Convert.ToInt16(TotalMaxQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } } #endregion #region Scheme Free Lines For PCS Free Qty // PCS Qty Scheme Filter Dv1 = new DataView(dt1); Dv1.RowFilter = "SCHEMECODE='" + drv.Row["SCHEMECODE"] + "' and [Scheme Item Type]='" + drv.Row["Scheme Item Type"] + "' and MINIMUMQUANTITY='" + drv.Row["MINIMUMQUANTITY"] + "' AND FREEQTYPCS>0"; foreach (DataRowView drv2 in Dv1) { TotalQtyofGroupItem = GetQtyofGroupItem(drv2["Scheme Item group"].ToString(), "BOX"); TotalQtyofItem = GetQtyofItem(drv2["Scheme Item group"].ToString(), "BOX"); TotalMaxQtyofItem = GetMaxQtyofItem("BOX"); if (drv["Scheme Item Type"].ToString() == "Group" && TotalQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITY"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITY"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalPCSQtyofGroupItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "Item" && TotalQtyofItem >= Convert.ToInt16(drv["MINIMUMQUANTITY"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofItem / Convert.ToInt16(drv2["MINIMUMQUANTITY"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "All" && TotalQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITY"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITY"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalMaxQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } } #endregion } intCalRemFreeQty = +1; } } #endregion #region For PCS Qty view = new DataView(dt1); view.RowFilter = "[Scheme Type]=0"; distinctTable = (DataTable)view.ToTable(true, "SCHEMECODE", "Scheme Item Type", "MINIMUMQUANTITYPCS"); dvSort = new DataView(distinctTable); dvSort.Sort = "SCHEMECODE ASC,MINIMUMQUANTITYPCS DESC"; Dv1 = null; intCalRemFreeQty = 0; RemainingQty = 0; schemeCode = ""; foreach (DataRowView drv in dvSort) { if (schemeCode != drv.Row["SCHEMECODE"].ToString()) { intCalRemFreeQty = 0; schemeCode = drv.Row["SCHEMECODE"].ToString(); } if (intCalRemFreeQty == 0) { #region Scheme Free Lines BOX Free Qty Dv1 = new DataView(dt1); Dv1.RowFilter = "SCHEMECODE='" + drv.Row["SCHEMECODE"] + "' and [Scheme Item Type]='" + drv.Row["Scheme Item Type"] + "' and MINIMUMQUANTITYPCS='" + drv.Row["MINIMUMQUANTITYPCS"] + "' AND FREEQTY>0 AND MINIMUMQUANTITYPCS>0"; foreach (DataRowView drv2 in Dv1) { TotalPCSQtyofGroupItem = GetQtyofGroupItem(drv2["Scheme Item group"].ToString(), "PCS"); TotalPCSQtyofItem = GetQtyofItem(drv2["Scheme Item group"].ToString(), "PCS"); TotalMaxPCSQtyofItem = GetMaxQtyofItem("PCS"); if (drv["Scheme Item Type"].ToString() == "Group" && TotalPCSQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITYPCS"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalQtyofGroupItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "Item" && TotalPCSQtyofItem >= Convert.ToInt16(drv["MINIMUMQUANTITYPCS"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofItem / Convert.ToInt16(drv2["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "All" && TotalPCSQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITYPCS"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalMaxQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } } #endregion #region Scheme Free Lines PCS Free Qty Dv1 = new DataView(dt1); Dv1.RowFilter = "SCHEMECODE='" + drv.Row["SCHEMECODE"] + "' and [Scheme Item Type]='" + drv.Row["Scheme Item Type"] + "' and MINIMUMQUANTITYPCS='" + drv.Row["MINIMUMQUANTITYPCS"] + "' AND FREEQTYPCS>0 AND MINIMUMQUANTITYPCS>0"; foreach (DataRowView drv2 in Dv1) { TotalPCSQtyofGroupItem = GetQtyofGroupItem(drv2["Scheme Item group"].ToString(), "PCS"); TotalPCSQtyofItem = GetQtyofItem(drv2["Scheme Item group"].ToString(), "PCS"); TotalMaxPCSQtyofItem = GetMaxQtyofItem("PCS"); if (drv["Scheme Item Type"].ToString() == "Group" && TotalPCSQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITYPCS"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalQtyofGroupItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "Item" && TotalPCSQtyofItem >= Convert.ToInt16(drv["MINIMUMQUANTITYPCS"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofItem / Convert.ToInt16(drv2["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } if (drv["Scheme Item Type"].ToString() == "All" && TotalPCSQtyofGroupItem >= Convert.ToInt16(drv["MINIMUMQUANTITYPCS"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalPCSQtyofGroupItem / Convert.ToInt16(drv2["MINIMUMQUANTITYPCS"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); //RemainingQty = Convert.ToInt16(TotalMaxQtyofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMQUANTITY"])); } } #endregion } intCalRemFreeQty += 1; } #endregion #region for Value DataView viewValue = new DataView(dt1); viewValue.RowFilter = "[Scheme Type]=1"; DataTable distinctTableValue = (DataTable)viewValue.ToTable(true, "SCHEMECODE", "Scheme Item Type", "MINIMUMVALUE"); DataView dvSortValue = new DataView(distinctTableValue); dvSortValue.Sort = "SCHEMECODE ASC,MINIMUMVALUE DESC"; DataView Dv1Value = null; Int16 IntCalRemFreeValue = 0; Int16 RemainingQtyValue = 0; schemeCode = ""; foreach (DataRowView drv in dvSortValue) { if (schemeCode != drv.Row["SCHEMECODE"].ToString()) { IntCalRemFreeValue = 0; schemeCode = drv.Row["SCHEMECODE"].ToString(); } if (IntCalRemFreeValue == 0) { Dv1Value = new DataView(dt1); Dv1Value.RowFilter = "SCHEMECODE='" + drv.Row["SCHEMECODE"] + "' AND [Scheme Item Type]='" + drv.Row["Scheme Item Type"] + "' and MINIMUMVALUE >='" + drv.Row["MINIMUMVALUE"] + "'"; foreach (DataRowView drv2 in Dv1Value) { TotalValueofGroupItem = GetValueofGroupItem(drv2["Scheme Item group"].ToString()); TotalValueofItem = GetValueofItem(drv2["Scheme Item group"].ToString()); TotalMaxValueofItem = GetMaxValueofItem(); if (Convert.ToInt16(drv2["FREEQTY"]) > 0) { if (drv["Scheme Item Type"].ToString() == "Group" && TotalValueofGroupItem >= Convert.ToInt16(drv["MINIMUMVALUE"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToInt16(drv2["MINIMUMVALUE"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); RemainingQtyValue = Convert.ToInt16(TotalValueofGroupItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMVALUE"])); } if (drv["Scheme Item Type"].ToString() == "Item" && TotalValueofItem >= Convert.ToInt16(drv["MINIMUMVALUE"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofItem / Convert.ToInt16(drv2["MINIMUMVALUE"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); RemainingQtyValue = Convert.ToInt16(TotalValueofItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMVALUE"])); } if (drv["Scheme Item Type"].ToString() == "All" && TotalValueofGroupItem >= Convert.ToInt16(drv["MINIMUMVALUE"])) { drv2["TotalFreeQty"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToInt16(drv2["MINIMUMVALUE"]))) * Convert.ToInt16(drv2["FREEQTY"])); dt3.ImportRow(drv2.Row); RemainingQtyValue = Convert.ToInt16(TotalValueofGroupItem - (Convert.ToInt16(drv2["TotalFreeQty"]) / Convert.ToInt16(drv2["FREEQTY"])) * Convert.ToInt16(drv2["MINIMUMVALUE"])); } } if (Convert.ToInt16(drv2["FREEQTYPCS"]) > 0) { if (drv["Scheme Item Type"].ToString() == "Group" && TotalValueofGroupItem >= Convert.ToInt16(drv["MINIMUMVALUE"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToInt16(drv2["MINIMUMVALUE"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); } if (drv["Scheme Item Type"].ToString() == "Item" && TotalValueofItem >= Convert.ToInt16(drv["MINIMUMVALUE"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofItem / Convert.ToInt16(drv2["MINIMUMVALUE"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); } if (drv["Scheme Item Type"].ToString() == "All" && TotalValueofGroupItem >= Convert.ToInt16(drv["MINIMUMVALUE"])) { drv2["TotalFreeQtyPCS"] = Convert.ToInt16(System.Math.Floor(Convert.ToDecimal(TotalValueofGroupItem / Convert.ToInt16(drv2["MINIMUMVALUE"]))) * Convert.ToInt16(drv2["FREEQTYPCS"])); dt3.ImportRow(drv2.Row); } } } IntCalRemFreeValue += 1; } } #endregion // Update Slab Qty For FreeQTYPCS foreach (DataColumn col in dt3.Columns) { if (col.ColumnName == "FREEQTY") { col.ReadOnly = false; } } for (int i = 0; i <= dt3.Rows.Count - 1; i++) { if (Convert.ToDecimal(dt3.Rows[i]["FREEQTYPCS"].ToString()) > 0) { dt3.Rows[i]["FREEQTY"] = Convert.ToInt32(dt3.Rows[i]["FREEQTYPCS"]); } } dt3.AcceptChanges(); DataView dv = dt3.DefaultView; dv.Sort = "SCHEMECODE ASC,SetNo ASC, FREEQTY ASC"; DataTable sortedDT = dv.ToTable(); return sortedDT; } else { return null; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); return null; } finally { conn.Close(); conn.Dispose(); } } public DataTable GetDatafromSPDiscount(string SPName, string strItem) { DataTable dt = new DataTable(); conn = baseObj.GetConnection(); try { string ItemGroup = string.Empty; string ItemCode = string.Empty; string strSite = Session["SiteCode"].ToString(); string strLocation = Session["SCHSTATE"].ToString(); cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandTimeout = 3600; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = SPName; cmd.Parameters.AddWithValue("@PLACESITE", strSite); cmd.Parameters.AddWithValue("@PLACESTATE", strLocation); cmd.Parameters.AddWithValue("@PLACEALL", ""); cmd.Parameters.AddWithValue("@CUSCODECUS", drpCustomerCode.SelectedValue.ToString()); cmd.Parameters.AddWithValue("@CUSCODEGROUP", drpCustomerGroup.SelectedValue.ToString()); cmd.Parameters.AddWithValue("@CUSCODEALL", ""); cmd.Parameters.AddWithValue("@ITEMITEM", strItem); cmd.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString()); //cmd.Parameters.AddWithValue("@ITEMGROUP",DDLProductGroup.SelectedValue.ToString()); cmd.Parameters.AddWithValue("@ITEMALL", ""); dt.Load(cmd.ExecuteReader()); } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } finally { conn.Close(); conn.Dispose(); } return dt; } public Int16 GetQtyofGroupItem(string Group, string BoxPCS) { DataTable dt; if (Group.Trim().Length == 0 || Group.Trim().ToUpper() == "ALL") { dt = baseObj.GetData("Select DISTINCT ITEMID From AX.ACXFreeItemGroupTable Where DATAAREAID='" + Session["DATAAREAID"] + "'"); } else { dt = baseObj.GetData("Select DISTINCT ITEMID From AX.ACXFreeItemGroupTable Where [GROUP] ='" + Group + "' and DATAAREAID='" + Session["DATAAREAID"] + "'"); } Int16 Qty = 0; foreach (DataRow dtdr in dt.Rows) { foreach (GridViewRow gvrow in gvDetails.Rows) { TextBox txtQty = (TextBox)gvrow.Cells[6].FindControl("txtBoxQtyGrid"); TextBox txtQtyPcs = (TextBox)gvrow.Cells[6].FindControl("txtPcsQtyGrid"); Label lblItem = (Label)gvrow.Cells[2].FindControl("Product"); string[] arritem = lblItem.Text.Split('-'); string strItemCode = arritem[0].ToString().Trim(); if (dtdr[0].ToString() == strItemCode) { if (BoxPCS == "BOX") { Qty += Convert.ToInt16(Convert.ToDouble(txtQty.Text)); } else { Qty += Convert.ToInt16(Convert.ToDouble(txtQtyPcs.Text)); } //Qty += Convert.ToInt16(Convert.ToDouble(txtQty.Text)); } } } return Qty; } public decimal GetValueofGroupItem(string Group) { DataTable dt; if (Group.Trim().Length == 0 || Group.Trim().ToUpper() == "ALL") { dt = baseObj.GetData("Select ITEMID From AX.ACXFreeItemGroupTable Where DATAAREAID='" + Session["DATAAREAID"] + "'"); } else { dt = baseObj.GetData("Select ITEMID From AX.ACXFreeItemGroupTable Where [GROUP] ='" + Group + "' and DATAAREAID='" + Session["DATAAREAID"] + "'"); } decimal Value = 0; foreach (DataRow dtdr in dt.Rows) { foreach (GridViewRow gvrow in gvDetails.Rows) { Label lblAmount = (Label)gvrow.Cells[6].FindControl("Amount"); Label lblItem = (Label)gvrow.Cells[2].FindControl("Product"); Label lblSchemeDiscVal = (Label)gvrow.Cells[2].FindControl("lblSchemeDiscVal"); string[] arritem = lblItem.Text.Split('-'); string strItemCode = arritem[0].ToString().Trim(); if (dtdr[0].ToString() == strItemCode) { Value += Convert.ToDecimal(lblAmount.Text) + Convert.ToDecimal(lblSchemeDiscVal.Text); } } } return Value; } public Int16 GetQtyofItem(string Item, string BoxPCS) { Int16 Qty = 0; foreach (GridViewRow gvrow in gvDetails.Rows) { TextBox txtQty = (TextBox)gvrow.Cells[6].FindControl("txtBoxQtyGrid"); TextBox txtQtyPcs = (TextBox)gvrow.Cells[6].FindControl("txtPcsQtyGrid"); Label lblItem = (Label)gvrow.Cells[2].FindControl("Product"); string[] arritem = lblItem.Text.Split('-'); string strItemCode = arritem[0].ToString().Trim(); if (strItemCode == Item) { // Qty = Convert.ToInt16(Convert.ToDouble(txtQty.Text)); if (BoxPCS == "BOX") { Qty += Convert.ToInt16(Convert.ToDouble(txtQty.Text)); } else { Qty += Convert.ToInt16(Convert.ToDouble(txtQtyPcs.Text)); } } } return Qty; } public decimal GetValueofItem(string Item) { decimal Value = 0; foreach (GridViewRow gvrow in gvDetails.Rows) { Label lblAmount = (Label)gvrow.Cells[6].FindControl("Total"); Label lblItem = (Label)gvrow.Cells[2].FindControl("Product"); Label lblSchemeDiscVal = (Label)gvrow.Cells[2].FindControl("lblSchemeDiscVal"); string[] arritem = lblItem.Text.Split('-'); string strItemCode = arritem[0].ToString().Trim(); if (strItemCode == Item) { //Value = Convert.ToDecimal(lblAmount.Text); Value = Convert.ToDecimal(lblAmount.Text) + Convert.ToDecimal(lblSchemeDiscVal.Text); } } return Value; } public Int16 GetMaxQtyofItem(string BoxPCS) { Int16 Qty = 0; Int16[] arrQty = new Int16[gvDetails.Rows.Count]; foreach (GridViewRow gvrow in gvDetails.Rows) { TextBox txtQty = (TextBox)gvrow.Cells[6].FindControl("txtBoxQtyGrid"); TextBox txtQtyPcs = (TextBox)gvrow.Cells[6].FindControl("txtPcsQtyGrid"); // arrQty[gvrow.RowIndex] = Convert.ToInt16(Convert.ToDouble(txtQty.Text)); if (BoxPCS == "BOX") { arrQty[gvrow.RowIndex] = Convert.ToInt16(Convert.ToDecimal(txtQty.Text)); } else { arrQty[gvrow.RowIndex] = Convert.ToInt16(Convert.ToDecimal(txtQtyPcs.Text)); } } Qty = arrQty.Max(); return Qty; } public decimal GetMaxValueofItem() { decimal Value = 0; decimal[] arrValue = new decimal[gvDetails.Rows.Count]; foreach (GridViewRow gvrow in gvDetails.Rows) { Label lblAmount = (Label)gvrow.Cells[12].FindControl("Amount"); Label lblSchemeDiscVal = (Label)gvrow.Cells[2].FindControl("lblSchemeDiscVal"); //arrValue[gvrow.RowIndex] = Convert.ToDecimal(lblAmount.Text); arrValue[gvrow.RowIndex] = Convert.ToDecimal(lblAmount.Text) + Convert.ToDecimal(lblSchemeDiscVal.Text); } Value = arrValue.Max(); return Value; } //private bool GetPrevSelection(string SchemeCode, string SetNo) //{ // foreach (GridViewRow rw in gvScheme.Rows) // { // CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); // if (chkBx.Checked && rw.Cells[1].Text != SchemeCode) // { // return true; // } // if (chkBx.Checked && rw.Cells[1].Text == SchemeCode && rw.Cells[7].Text != SetNo) // { // return true; // } // } // return false; //} protected void chkSelect_CheckedChanged(object sender, EventArgs e) { CheckBox activeCheckBox = sender as CheckBox; GridViewRow row1 = (GridViewRow)activeCheckBox.Parent.Parent; String SchemeCode1 = row1.Cells[1].Text; String SetNo1 = row1.Cells[7].Text; if (Global.GetPrevSelection(SchemeCode1, SetNo1, ref gvScheme,"0")) { activeCheckBox.Checked = false; return; } TextBox txtQty = (TextBox)row1.FindControl("txtQty"); TextBox txtQtyPcs = (TextBox)row1.FindControl("txtQtyPcs"); string SchemeCode; string SetNo; //CheckBox activeCheckBox = sender as CheckBox; #region For Selection If checked if (activeCheckBox.Checked) { //GridViewRow row = (GridViewRow)(((CheckBox)sender)).NamingContainer; //string SchemeCode = row.Cells[1].Text; GridViewRow row = (GridViewRow)(((CheckBox)sender)).NamingContainer; SchemeCode = row.Cells[1].Text; SetNo = row.Cells[7].Text; foreach (GridViewRow rw in gvScheme.Rows) { #region Same Scheme Validation 1st Check //CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); //if (chkBx.Checked) //{ // if (rw.Cells[1].Text != SchemeCode) // { // activeCheckBox.Checked = false; // string message = "alert('You can select only one scheme items !');"; // ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true); // return; // } // else if (rw.Cells[1].Text == SchemeCode && SetNo != rw.Cells[7].Text) // { // activeCheckBox.Checked = false; // string message = "alert('You can select only one scheme items with same set!');"; // ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true); // return; // } //} #endregion #region 2nd Check Same scheme and same set setno > 0 Auto select all scheme CheckBox chkBxNew = (CheckBox)rw.FindControl("chkSelect"); //Auto Select All Same Set No if (Convert.ToString(rw.Cells[7].Text) == SetNo && rw.Cells[1].Text == SchemeCode && Convert.ToInt16(SetNo) > 0) { chkBxNew.Checked = true; txtQty = (TextBox)rw.FindControl("txtQty"); txtQtyPcs = (TextBox)rw.FindControl("txtQtyPcs"); HiddenField hdnTotalFreeQty = (HiddenField)rw.FindControl("hdnTotalFreeQty"); HiddenField hdnTotalFreeQtyPcs = (HiddenField)rw.FindControl("hdnTotalFreeQtyPcs"); txtQty.Text = hdnTotalFreeQty.Value; txtQtyPcs.Text = hdnTotalFreeQtyPcs.Value; txtQty.Enabled = false; txtQtyPcs.Enabled = false; } #endregion } #region FreeBox Readonly validation foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); txtQty = (TextBox)rw.FindControl("txtQty"); if (chkBx.Checked) { txtQty.ReadOnly = false; } else { txtQty.Text = string.Empty; txtQty.ReadOnly = true; } } #endregion #region checkbox enable for set no 0 only if (SetNo1 == "0") { txtQty = (TextBox)row1.FindControl("txtQty"); txtQtyPcs = (TextBox)row1.FindControl("txtQtyPcs"); HiddenField hdnTotalFreeQty = (HiddenField)row1.FindControl("hdnTotalFreeQty"); HiddenField hdnTotalFreeQtyPcs = (HiddenField)row1.FindControl("hdnTotalFreeQtyPcs"); if (hdnTotalFreeQty.Value != "") { txtQty.ReadOnly = false; } else { txtQty.ReadOnly = true; } if (Session["ApplicableOnState"].ToString() == "Y") { if (hdnTotalFreeQtyPcs.Value != "") { txtQtyPcs.ReadOnly = false; } else { txtQtyPcs.ReadOnly = true; } } else { txtQtyPcs.ReadOnly = true; } } #endregion } else { #region For unchecked foreach (GridViewRow rw in gvScheme.Rows) { GridViewRow row = (GridViewRow)(((CheckBox)sender)).NamingContainer; SchemeCode = row.Cells[1].Text; SetNo = row.Cells[7].Text; if (SchemeCode == SchemeCode1 && SetNo == SetNo1 && Convert.ToInt16(SetNo) > 0) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); chkBx.Checked = false; txtQty = (TextBox)rw.FindControl("txtQty"); txtQtyPcs = (TextBox)rw.FindControl("txtQtyPcs"); HiddenField hdnTotalFreeQty = (HiddenField)rw.FindControl("hdnTotalFreeQty"); HiddenField hdnTotalFreeQtyPcs = (HiddenField)rw.FindControl("hdnTotalFreeQtyPcs"); txtQty.Text = ""; txtQtyPcs.Text = ""; txtQtyPcs.ReadOnly = true; txtQty.ReadOnly = true; } } if (SetNo1 == "0") { txtQty = (TextBox)row1.FindControl("txtQty"); txtQtyPcs = (TextBox)row1.FindControl("txtQtyPcs"); txtQty.Text = ""; txtQtyPcs.Text = ""; } #endregion } #endregion if (activeCheckBox.Checked) { if (Convert.ToInt32(SetNo1) > 0) { foreach (GridViewRow rw in gvScheme.Rows) { if (Convert.ToString(rw.Cells[7].Text) == SetNo1 && rw.Cells[1].Text == SchemeCode1) { txtQty = (TextBox)rw.FindControl("txtQty"); txtQtyPcs = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Enabled = false; txtQtyPcs.Enabled = false; } } } else { txtQty.Enabled = true; txtQtyPcs.Enabled = true; } } else { txtQty.Enabled = false; txtQtyPcs.Enabled = false; txtQty.Text = "0"; txtQtyPcs.Text = "0"; } SchemeDiscCalculation(); DataTable dt1 = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt1 = (DataTable)Session["InvLineItem"]; } GridViewFooterCalculate(dt1); } public void GetSelectedShemeItemChecked(string SchemeCode, string FreeitemCode, Int16 Qty, Int16 Slab,Int16 QtyPcs) { foreach (GridViewRow rw in gvScheme.Rows) { if (rw.Cells[1].Text == SchemeCode && rw.Cells[4].Text == FreeitemCode && Convert.ToInt16(Convert.ToDouble(rw.Cells[6].Text)) == Slab) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); chkBx.Checked = true; TextBox txtQty = (TextBox)rw.FindControl("txtQty"); TextBox txtQtyPcs = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Text = Convert.ToString(Qty); txtQtyPcs.Text = Convert.ToString(QtyPcs); chkSelect_CheckedChanged(chkBx, new EventArgs()); if (chkBx.Checked==false) { txtQty.Text = "0"; txtQtyPcs.Text = "0"; } //chkSelect_CheckedChanged(this, new EventArgs()); } } } protected void txtQty_TextChanged(object sender, EventArgs e) { int TotalQty = 0; GridViewRow row = (GridViewRow)(((TextBox)sender)).NamingContainer; string SchemeCode = row.Cells[1].Text; int AvlFreeQty = Convert.ToInt16(row.Cells[8].Text); int Slab = Convert.ToInt16(row.Cells[6].Text); CheckBox chkBx1 = (CheckBox)row.FindControl("chkSelect"); TextBox txtQty1 = (TextBox)row.FindControl("txtQty"); foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); TextBox txtQty = (TextBox)rw.FindControl("txtQty"); if (chkBx.Checked == true) { if (!string.IsNullOrEmpty(txtQty.Text) && rw.Cells[1].Text == SchemeCode && Convert.ToInt16(rw.Cells[6].Text) == Slab) { TotalQty += Convert.ToInt16(txtQty.Text); if (getBoxPcsPicQty(SchemeCode, Slab, "P") > 0) { txtQty1.Text = "0"; chkBx1.Checked = false; txtQty1.ReadOnly = false; string message = "alert('Free Qty should not greater than available free qty !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } if (TotalQty > AvlFreeQty) { txtQty1.Text = "0"; chkBx1.Checked = false; txtQty1.ReadOnly = false; string message = "alert('Free Qty should not greater than available free qty !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } else { txtQty.Text = "0"; } } this.SchemeDiscCalculation(); DataTable dt1 = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt1 = (DataTable)Session["InvLineItem"]; } GridViewFooterCalculate(dt1); } private void GridViewFooterCalculate(DataTable dt) { //For Total[Sum] Value Show in Footer--// string st = Convert.ToString(dt.Rows[0]["TD"].GetType()); decimal tSoQtyBox = dt.AsEnumerable().Sum(row => row.Field<decimal>("So_Qty")); decimal tInvoiceQtyBox = dt.AsEnumerable().Sum(row => row.Field<decimal>("Invoice_Qty")); decimal tBoxQty = dt.AsEnumerable().Sum(row => row.Field<decimal>("Box_Qty")); decimal tPcsQty = dt.AsEnumerable().Sum(row => row.Field<decimal>("Pcs_Qty")); decimal tLtr = dt.AsEnumerable().Sum(row => row.Field<decimal>("Ltr")); decimal tDiscValue = dt.AsEnumerable().Sum(row => row.Field<decimal>("DiscVal")); decimal tTaxAmount = dt.AsEnumerable().Sum(row => row.Field<decimal>("TaxValue")); decimal tAddTaxAmount = dt.AsEnumerable().Sum(row => row.Field<decimal>("ADDTaxValue")); decimal tSecDiscAmount = dt.AsEnumerable().Sum(row => row.Field<decimal>("SecDiscAmount")); decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>("Amount")); decimal TD = dt.AsEnumerable().Sum(row => row.Field<decimal>("TD")); decimal AllTotal = dt.AsEnumerable().Sum(row => row.Field<decimal>("Total")); gvDetails.FooterRow.Cells[4].HorizontalAlign = HorizontalAlign.Left; gvDetails.FooterRow.Cells[4].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[4].Text = "TOTAL"; gvDetails.FooterRow.Cells[4].Font.Bold = true; //gvDetails.FooterRow.Cells[18].HorizontalAlign = HorizontalAlign.Right; //gvDetails.FooterRow.Cells[18].ForeColor = System.Drawing.Color.MidnightBlue; //gvDetails.FooterRow.Cells[18].Text = total.ToString("N2"); //gvDetails.FooterRow.Cells[18].Font.Bold = true; gvDetails.FooterRow.Cells[5].HorizontalAlign = HorizontalAlign.Center; gvDetails.FooterRow.Cells[5].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[5].Text = tSoQtyBox.ToString("N2"); gvDetails.FooterRow.Cells[5].Font.Bold = true; gvDetails.FooterRow.Cells[6].HorizontalAlign = HorizontalAlign.Center; gvDetails.FooterRow.Cells[6].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[6].Text = tBoxQty.ToString("N2"); gvDetails.FooterRow.Cells[6].Font.Bold = true; gvDetails.FooterRow.Cells[7].HorizontalAlign = HorizontalAlign.Center; gvDetails.FooterRow.Cells[7].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[7].Text = tPcsQty.ToString("N2"); gvDetails.FooterRow.Cells[7].Font.Bold = true; gvDetails.FooterRow.Cells[8].HorizontalAlign = HorizontalAlign.Left; gvDetails.FooterRow.Cells[8].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[8].Text = tInvoiceQtyBox.ToString("N2"); gvDetails.FooterRow.Cells[8].Font.Bold = true; gvDetails.FooterRow.Cells[11].HorizontalAlign = HorizontalAlign.Right; gvDetails.FooterRow.Cells[11].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[11].Text = tLtr.ToString("N2"); gvDetails.FooterRow.Cells[11].Font.Bold = true; gvDetails.FooterRow.Cells[14].HorizontalAlign = HorizontalAlign.Right; gvDetails.FooterRow.Cells[14].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[14].Text = tTaxAmount.ToString("N2"); gvDetails.FooterRow.Cells[14].Font.Bold = true; gvDetails.FooterRow.Cells[16].HorizontalAlign = HorizontalAlign.Right; gvDetails.FooterRow.Cells[16].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[16].Text = tAddTaxAmount.ToString("N2"); gvDetails.FooterRow.Cells[16].Font.Bold = true; gvDetails.FooterRow.Cells[18].HorizontalAlign = HorizontalAlign.Right; gvDetails.FooterRow.Cells[18].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[18].Text = tDiscValue.ToString("N2"); gvDetails.FooterRow.Cells[18].Font.Bold = true; //gvDetails.FooterRow.Cells[23].HorizontalAlign = HorizontalAlign.Right; //gvDetails.FooterRow.Cells[23].ForeColor = System.Drawing.Color.MidnightBlue; //gvDetails.FooterRow.Cells[23].Text = TD.ToString("N2"); //gvDetails.FooterRow.Cells[23].Font.Bold = true; gvDetails.FooterRow.Cells[28].HorizontalAlign = HorizontalAlign.Right; gvDetails.FooterRow.Cells[28].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[28].Text = AllTotal.ToString("N2"); gvDetails.FooterRow.Cells[28].Font.Bold = true; gvDetails.FooterRow.Cells[22].HorizontalAlign = HorizontalAlign.Right; gvDetails.FooterRow.Cells[22].ForeColor = System.Drawing.Color.MidnightBlue; gvDetails.FooterRow.Cells[22].Text = tSecDiscAmount.ToString("N2"); gvDetails.FooterRow.Cells[22].Font.Bold = true; CalculateInvoiceValue(); } protected void ddlProductGroup_SelectedIndexChanged(object sender, EventArgs e) { strQuery = @"Select distinct P.PRODUCT_SUBCATEGORY as Name,P.PRODUCT_SUBCATEGORY as Code from ax.InventTable P " + "where P.PRODUCT_GROUP='" + DDLProductGroup.SelectedItem.Value + "' and P.block=0"; DDLProductSubCategory.Items.Clear(); DDLProductSubCategory.Items.Add("Select..."); baseObj.BindToDropDown(DDLProductSubCategory, strQuery, "Name", "Code"); FillProductCode(); DDLProductSubCategory.Focus(); PcsBillingApplicable(); } protected void DDLProductSubCategory_SelectedIndexChanged(object sender, EventArgs e) { strQuery = "Select distinct P.ITEMID+'-'+P.Product_Name as Name,P.ITEMID from ax.InventTable P where Product_Group='" + DDLProductGroup.SelectedValue + "' and P.block=0 and P.PRODUCT_SUBCATEGORY ='" + DDLProductSubCategory.SelectedItem.Value + "'"; //--AND SITE_CODE='657546'"; DDLMaterialCode.DataSource = null; DDLMaterialCode.Items.Clear(); // DDLMaterialCode.Items.Add("Select..."); baseObj.BindToDropDown(DDLMaterialCode, strQuery, "Name", "ITEMID"); txtQtyBox.Text = string.Empty; txtQtyCrates.Text = string.Empty; txtLtr.Text = string.Empty; txtPrice.Text = string.Empty; txtValue.Text = string.Empty; txtEnterQty.Text = string.Empty; DDLMaterialCode.Enabled = true; DDLMaterialCode.SelectedIndex = 0; //DDLMaterialCode.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;"); DDLMaterialCode.Focus(); /* Modified 29-03-2017 */ string a = sender.ToString(); string b = e.ToString(); txtQtyBox.Text = "0"; txtBoxqty.Text = "0"; txtQtyCrates.Text = "0"; txtLtr.Text = "0.00"; txtPrice.Text = "0.00"; txtValue.Text = "0.00"; txtEnterQty.Text = "0.00"; txtViewTotalBox.Text = "0.00"; txtBoxPcs.Text = "0.00"; DataTable dt = new DataTable(); strQuery = " Select ISNULL(coalesce(cast(sum(F.TransQty) as decimal(10,2)),0),0) as TransQty,cast(G.Product_PackSize as decimal(10,2)) as Product_PackSize,cast(G.Product_MRP as decimal(10,2)) as Product_MRP ,Cast(G.Product_Crate_PackSize as decimal(10,2)) as Product_CrateSize" + " from [ax].[ACXINVENTTRANS] F " + " Left Join ax.InventTable G on G.ItemId=F.[ProductCode] " + " where F.[SiteCode]='" + Session["SiteCode"].ToString() + "' and G.block=0 and F.[ProductCode]='" + DDLMaterialCode.SelectedItem.Value + "' and F.[TransLocation]='" + Session["TransLocation"].ToString() + "' " + " group by G.Product_PackSize,G.Product_MRP,G.Product_Crate_PackSize "; dt = baseObj.GetData(strQuery); if (dt.Rows.Count > 0) { txtStockQty.Text = Convert.ToDecimal(dt.Rows[0]["TransQty"].ToString()).ToString(); txtPack.Text = dt.Rows[0]["Product_PackSize"].ToString(); txtMRP.Text = dt.Rows[0]["Product_MRP"].ToString(); txtCrateSize.Text = dt.Rows[0]["Product_CrateSize"].ToString(); ProductSubCategory(); } else { txtStockQty.Text = "0.00"; txtPack.Text = "0"; txtMRP.Text = "0.00"; txtCrateSize.Text = "0.00"; } txtQtyBox.Focus(); // DataTable dt = new DataTable(); string query = "select Product_Group,PRODUCT_SUBCATEGORY from ax.INVENTTABLE where ItemId='" + DDLMaterialCode.SelectedItem.Value + "' and block=0 order by Product_Name"; dt = baseObj.GetData(query); if (dt.Rows.Count > 0) { DDLProductGroup.Text = dt.Rows[0]["PRODUCT_GROUP"].ToString(); ProductSubCategory(); DDLProductSubCategory.Text = dt.Rows[0]["PRODUCT_SUBCATEGORY"].ToString(); } txtEnterQty.Focus(); PcsBillingApplicable(); } protected void DDLMaterialCode_SelectedIndexChanged(object sender, EventArgs e) { string a = sender.ToString(); string b = e.ToString(); txtQtyBox.Text = "0"; txtBoxqty.Text = "0"; txtQtyCrates.Text = "0"; txtLtr.Text = "0.00"; txtPrice.Text = "0.00"; txtValue.Text = "0.00"; txtEnterQty.Text = "0.00"; txtViewTotalBox.Text = "0.00"; txtBoxPcs.Text = "0.00"; DataTable dt = new DataTable(); strQuery = " Select ISNULL(coalesce(cast(sum(F.TransQty) as decimal(10,2)),0),0) as TransQty,cast(G.Product_PackSize as decimal(10,2)) as Product_PackSize,cast(G.Product_MRP as decimal(10,2)) as Product_MRP ,Cast(G.Product_Crate_PackSize as decimal(10,2)) as Product_CrateSize" + " from [ax].[ACXINVENTTRANS] F " + " Left Join ax.InventTable G on G.ItemId=F.[ProductCode] " + " where F.[SiteCode]='" + Session["SiteCode"].ToString() + "' and G.block=0 and F.[ProductCode]='" + DDLMaterialCode.SelectedItem.Value + "' and F.[TransLocation]='" + Session["TransLocation"].ToString() + "' " + " group by G.Product_PackSize,G.Product_MRP,G.Product_Crate_PackSize "; dt = baseObj.GetData(strQuery); if (dt.Rows.Count > 0) { txtStockQty.Text = Convert.ToDecimal(dt.Rows[0]["TransQty"].ToString()).ToString(); txtPack.Text = dt.Rows[0]["Product_PackSize"].ToString(); txtMRP.Text = dt.Rows[0]["Product_MRP"].ToString(); txtCrateSize.Text = dt.Rows[0]["Product_CrateSize"].ToString(); ProductSubCategory(); } else { txtStockQty.Text = "0.00"; txtPack.Text = "0"; txtMRP.Text = "0.00"; txtCrateSize.Text = "0.00"; } try { string[] calValue = baseObj.CalculatePrice1(DDLMaterialCode.SelectedItem.Value, drpCustomerCode.SelectedItem.Value, 1, ddlEntryType.SelectedItem.Value); if (calValue[0] == "") { lblMessage.Text = "Price Not Define !"; ScriptManager.RegisterStartupScript(this, typeof(Page), "Validation", "alert('Price not defined!');", true); } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); string message = "alert('" + ex.Message.ToString() + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } txtQtyBox.Focus(); // DataTable dt = new DataTable(); string query = "select Product_Group,PRODUCT_SUBCATEGORY from ax.INVENTTABLE where ItemId='" + DDLMaterialCode.SelectedItem.Value + "' order by Product_Name"; dt = baseObj.GetData(query); if (dt.Rows.Count > 0) { DDLProductGroup.Text = dt.Rows[0]["PRODUCT_GROUP"].ToString(); ProductSubCategory(); DDLProductSubCategory.Text = dt.Rows[0]["PRODUCT_SUBCATEGORY"].ToString(); } txtEnterQty.Focus(); PcsBillingApplicable(); } public void ProductSubCategory() { strQuery = @"Select distinct P.PRODUCT_SUBCATEGORY as Name,P.PRODUCT_SUBCATEGORY as Code from ax.InventTable P " + "where P.PRODUCT_GROUP='" + DDLProductGroup.SelectedItem.Value + "' and P.block=0"; DDLProductSubCategory.Items.Clear(); DDLProductSubCategory.Items.Add("Select..."); baseObj.BindToDropDown(DDLProductSubCategory, strQuery, "Name", "Code"); // FillProductCode(); DDLProductSubCategory.Focus(); } protected void BtnAddItem_Click(object sender, EventArgs e) { DDLMaterialCode.Focus(); lblMessage.Text = string.Empty; //=============Validation================= foreach (GridViewRow grv in gvDetails.Rows) { //string product = grv.Cells[0].Text; HiddenField hdnproduct = (HiddenField)grv.Cells[0].FindControl("HiddenField2"); string product = hdnproduct.Value; if (DDLMaterialCode.SelectedItem.Value == product) { txtEnterQty.Text = ""; txtQtyBox.Text = ""; txtQtyCrates.Text = ""; txtLtr.Text = ""; txtPrice.Text = ""; txtValue.Text = ""; txtMRP.Text = ""; txtPack.Text = ""; txtStockQty.Text = ""; txtCrateQty.Text = ""; txtBoxqty.Text = ""; txtPCSQty.Text = ""; // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('" + DDLMaterialCode.SelectedItem.Text + " is already exists in the list .Please Select Another Product !!');", true); string message = "alert('" + DDLMaterialCode.SelectedItem.Text + " is already exists in the list .Please Select Another Product !!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } //============================ bool valid = true; valid = ValidateLineItemAdd(); //DataTable dt = new DataTable(); //dt = Session["ItemTable"] as DataTable; DataTable dt = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt = (DataTable)Session["InvLineItem"]; } if (valid == true) { dt = AddLineItems(); if (Msg.Rows.Count > 0) { string message = "alert('Error: Invalid Operation...!!!! ');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); ScriptManager.RegisterStartupScript(this, typeof(Page), "Validation", "alert('" + message.ToString().Replace("'","''") + "'", true); return; } if (dt.Rows.Count > 0) { gvDetails.DataSource = dt; gvDetails.DataBind(); gvDetails.Visible = true; if (txtSecDiscPer.Text.Trim().Length > 0 || txtSecDiscValue.Text.Trim().Length > 0) { btnGO_Click(sender, e); } if (txtTDValue.Text.Trim().Length>0) { btnApply_Click(sender, e); } GridViewFooterCalculate(dt); } else { gvDetails.DataSource = dt; gvDetails.DataBind(); gvDetails.Visible = false; } } //else //{ // gvDetails.DataSource = dt; // gvDetails.DataBind(); // gvDetails.Visible = true; // } //if (dt.Rows.Count > 0) //{ // gvDetails.DataSource = dt; // gvDetails.DataBind(); // gvDetails.Visible = true; // GridViewFooterCalculate(dt); //} //else //{ // gvDetails.DataSource = dt; // gvDetails.DataBind(); // gvDetails.Visible = false; //} txtEnterQty.Text = string.Empty; DataTable dtApplicable = baseObj.GetData("SELECT APPLICABLESCHEMEDISCOUNT from AX.ACXCUSTMASTER WHERE CUSTOMER_CODE = '" + drpCustomerCode.SelectedValue.ToString() + "'"); if (dtApplicable.Rows.Count > 0) { intApplicable = Convert.ToInt32(dtApplicable.Rows[0]["APPLICABLESCHEMEDISCOUNT"].ToString()); } if (intApplicable == 1 || intApplicable == 3) { foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkgrd = (CheckBox)rw.FindControl("chkSelect"); TextBox txtQty = (TextBox)rw.FindControl("txtQty"); TextBox txtQtyPCS = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Text = ""; txtQtyPCS.Text = ""; chkgrd.Checked = false; } this.SchemeDiscCalculation(); this.BindSchemeGrid(); } this.SchemeDiscCalculation(); DDLMaterialCode.Enabled = true; GridViewFooterCalculate(dt); //DDLMaterialCode.SelectedIndex = 0; // DDLMaterialCode.Focus(); } public void ProductGroup() { string strProductGroup = "Select Distinct a.Product_Group from ax.InventTable a where a.Product_Group <>'' AND A.BLOCK=0 order by a.Product_Group"; DDLProductGroup.Items.Clear(); DDLProductGroup.Items.Add("Select..."); baseObj.BindToDropDown(DDLProductGroup, strProductGroup, "Product_Group", "Product_Group"); } protected void txtQtyBox_TextChanged(object sender, EventArgs e) { try { string[] calValue = baseObj.CalculatePrice1(DDLMaterialCode.SelectedItem.Value, drpCustomerCode.SelectedItem.Value, int.Parse(txtEnterQty.Text), ddlEntryType.SelectedItem.Value); if (calValue[0] != "") { if (calValue[5] == "Box") { txtQtyBox.Text = txtEnterQty.Text; txtQtyCrates.Text = calValue[0]; if (Convert.ToDecimal(txtQtyBox.Text) > Convert.ToDecimal(txtStockQty.Text)) { //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Enter a valid number!!');", true); string message = "alert('Please Enter a valid number!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } if (calValue[5] == "Crate") { txtQtyCrates.Text = txtEnterQty.Text; txtQtyBox.Text = calValue[0]; } txtLtr.Text = calValue[1]; txtPrice.Text = calValue[2]; txtValue.Text = calValue[3]; lblHidden.Text = calValue[4]; BtnAddItem.Focus(); BtnAddItem.CausesValidation = false; // BtnAddItem.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(BtnAddItem, null) + ";"); } else { lblMessage.Text = "Price Not Define !"; } } catch (Exception ex) { // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Price Not Defined !');", true); // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('" + ex.Message.ToString() + "');", true); ErrorSignal.FromCurrentContext().Raise(ex); string message = "alert('" + ex.Message.ToString() + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } } private bool ValidateLineItemAdd() { bool b = true; if (DDLProductGroup.Text == "Select..." || DDLProductGroup.Text == "") { // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Select Material Group !');", true); string message = "alert('Select Material Group !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); DDLProductGroup.Focus(); b = false; return b; } if (DDLMaterialCode.Text == string.Empty || DDLMaterialCode.Text == "Select...") { //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Select Product First !');", true); string message = "alert('Select Product First !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); DDLMaterialCode.Focus(); b = false; return b; } if (txtQtyBox.Text == string.Empty || txtQtyBox.Text == "0") { b = false; string message = "alert('Qty cannot be left blank !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Qty cannot be left blank !');", true); return b; } if (Convert.ToDecimal(txtQtyBox.Text.Trim()) == 0) { b = false; string message = "alert('Please enter Qty!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return b; } if (txtStockQty.Text == string.Empty || txtStockQty.Text == "0") { b = false; //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Qty cannot be zero !');", true); string message = "alert('Stock Qty cannot be zero !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return b; } if (Convert.ToDecimal(txtQtyBox.Text) > Convert.ToDecimal(txtStockQty.Text)) { b = false; //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Box Qty should not greater than Stock Qty !');", true); string message = "alert('Box Qty should not greater than Stock Qty !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return b; } if (txtQtyCrates.Text == string.Empty) { b = false; //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Price cannot be left blank !');", true); string message = "alert('Price cannot be left blank !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return b; } if (txtLtr.Text == string.Empty || txtLtr.Text == "0") { b = false; // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('ltr cannot be left blank !');", true); string message = "alert('LTR cannot be left blank !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return b; } if (txtPrice.Text == string.Empty || txtPrice.Text == "0") { decimal amount; if (!decimal.TryParse(txtPrice.Text, out amount)) { b = false; //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Price is cannot be left blank !');", true); string message = "alert('Price is cannot be left blank !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return b; } if (Convert.ToDecimal(txtPrice.Text) <= 0) { b = false; //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Price is cannot be left blank !');", true); string message = "alert('Please Check Product Price !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return b; } else { b = true; } } return b; } private DataTable AddLineItems() { try { if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dtLineItems = (DataTable)Session["InvLineItem"]; } DataRow[] dataPerDay = (from myRow in dtLineItems.AsEnumerable() where myRow.Field<string>("Product_Code") == DDLMaterialCode.SelectedValue.ToString() select myRow).ToArray(); if (dataPerDay.Count() == 0) { #region check Bill to Address if (txtBillToState.Text.Trim().Length == 0) { string message = "alert('Please select Customer Bill To State!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return dtLineItems; } #endregion DataTable dtApplicable = baseObj.GetData("SELECT APPLICABLESCHEMEDISCOUNT from AX.ACXCUSTMASTER WHERE CUSTOMER_CODE = '" + drpCustomerCode.SelectedValue.ToString() + "'"); if (dtApplicable.Rows.Count > 0) { intApplicable = Convert.ToInt32(dtApplicable.Rows[0]["APPLICABLESCHEMEDISCOUNT"].ToString()); } #region Discount /////////////////////////////////// For ///////////////////////////////////////////////////// #endregion int count = gvDetails.Rows.Count; count = count + 1; DataTable dt = new DataTable(); /* ----------------Gst Implementation----------------*/ dt = baseObj.GetData("EXEC USP_ACX_GetSalesLineCalcGST '" + DDLMaterialCode.SelectedValue.ToString() + "','" + drpCustomerCode.SelectedValue.ToString() + "','" + Session["SiteCode"].ToString() + "'," + Convert.ToDecimal(txtQtyBox.Text.Trim()) + "," + Convert.ToDecimal(txtPrice.Text.Trim()) + ",'" + Session["SITELOCATION"].ToString() + "','" + drpCustomerGroup.SelectedValue.ToString() + "','" + Session["DATAAREAID"].ToString() + "'"); if (dt.Rows.Count > 0) { if (dt.Rows[0]["RETMSG"].ToString().IndexOf("FALSE") >= 0) { string message = "alert('" + dt.Rows[0]["RETMSG"].ToString().Replace("FALSE|", "") + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); DDLMaterialCode.Focus(); return dtLineItems; } DataRow row; row = dtLineItems.NewRow(); row["Product_Code"] = DDLMaterialCode.SelectedValue.ToString(); row["Line_No"] = count; row["Product"] = DDLMaterialCode.SelectedItem.Text.ToString(); row["Pack"] = txtPack.Text; row["So_Qty"] = "0"; row["Invoice_Qty"] = decimal.Parse(txtQtyBox.Text.Trim().ToString()); row["Box_Qty"] = Convert.ToDecimal(txtViewTotalBox.Text.Trim().ToString()); //Math.Truncate(decimal.Parse(txtQtyBox.Text.Trim().ToString())); row["Pcs_Qty"] = Convert.ToDecimal(txtViewTotalPcs.Text.Trim().ToString());// (decimal.Parse(txtQtyBox.Text.Trim().ToString()) - Math.Truncate(decimal.Parse(txtQtyBox.Text.Trim().ToString()))) * Global.ParseDecimal(txtPack.Text);//decimal.Parse(txtPCSQty.Text.Trim().ToString()); row["BoxPcs"] = Convert.ToDecimal(txtBoxPcs.Text.Trim()); row["Ltr"] = Convert.ToDecimal(txtLtr.Text.Trim().ToString()); //row["Rate"] = Convert.ToDecimal(txtPrice.Text.Trim().ToString()); row["Rate"] = Convert.ToDecimal(dt.Rows[0]["Rate"]); row["BasePrice"] = Convert.ToDecimal(txtPrice.Text.Trim()); row["Amount"] = Convert.ToDecimal(dt.Rows[0]["VALUE"]); //TotalValue.ToString("0.00"); if (dt.Rows[0]["DISCTYPE"].ToString() == "") { row["DiscType"] = 2; } else if (dt.Rows[0]["DISCTYPE"].ToString() == "Per") { row["DiscType"] = 0; } else if (dt.Rows[0]["DISCTYPE"].ToString() == "Val") { row["DiscType"] = 1; } row["ClaimDiscAmt"] = Convert.ToDecimal(dt.Rows[0]["ClaimDiscAmt"]); row["Disc"] = Convert.ToDecimal(dt.Rows[0]["DISC"]); row["DiscVal"] = Convert.ToDecimal(dt.Rows[0]["DISCVAL"]).ToString("0.00"); row["SchemeDisc"] = new decimal(0); row["SchemeDiscVal"] = new decimal(0); //==========For Tax=============== //row["TaxPer"] = Convert.ToDecimal(dt.Rows[0]["TAX_CODE"]); row["TaxPer"] = Convert.ToDecimal(dt.Rows[0]["TAX_PER"]); row["TaxValue"] = Convert.ToDecimal(dt.Rows[0]["TAX_AMOUNT"]).ToString("0.00"); //row["ADDTaxPer"] = Convert.ToDecimal(dt.Rows[0]["ADDTAX_CODE"]); row["ADDTaxPer"] = Convert.ToDecimal(dt.Rows[0]["ADDTAX_PER"]); row["ADDTaxValue"] = Convert.ToDecimal(dt.Rows[0]["ADDTAX_AMOUNT"]).ToString("0.00"); row["MRP"] = Convert.ToDecimal(dt.Rows[0]["MRP"]); row["TaxableAmount"] = Convert.ToDecimal(dt.Rows[0]["TaxableAmount"]); row["StockQty"] = decimal.Parse(txtStockQty.Text.Trim().ToString()); row["SchemeCode"] = ""; row["Total"] = Convert.ToDecimal(dt.Rows[0]["VALUE"]).ToString("0.00"); //TotalValue.ToString("0.00"); row["TD"] = "0.00"; row["PE"] = "0.00"; row["SecDiscPer"] = "0.00"; row["SecDiscAmount"] = "0.00"; row["SchemeDisc"] = "0.00"; row["SchemeDiscVal"] = "0.00"; /* ----- GST Implementation Start */ row["TaxComponent"] = dt.Rows[0]["TAX_CODE"].ToString(); row["AddTaxComponent"] = dt.Rows[0]["ADDTAX_CODE"].ToString(); row["HSNCode"] = dt.Rows[0]["HSNCODE"].ToString(); if (dt.Columns.Contains("CLAIMDISCAMT")) { row["CLAIMDISCAMT"] = dt.Rows[0]["CLAIMDISCAMT"].ToString(); } if (dt.Columns.Contains("TAX1COMPONENT")) { row["TAX1COMPONENT"] = dt.Rows[0]["TAX1COMPONENT"].ToString(); } if (dt.Columns.Contains("TAX2COMPONENT")) { row["TAX2COMPONENT"] = dt.Rows[0]["TAX2COMPONENT"].ToString(); } if (dt.Columns.Contains("TAX2")) { row["TAX2"] = dt.Rows[0]["TAX2"].ToString(); } if (dt.Columns.Contains("TAX2")) { row["TAX1"] = dt.Rows[0]["TAX1"].ToString(); } /* ----- GST Implementation End */ int intCalculation = 2; row["CalculationOn"] = dt.Rows[0]["DISCTYPE"].ToString(); if (dt.Rows[0]["CALCULATIONBASE"].ToString().ToUpper() == "PRICE") { intCalculation = 0; } else if (dt.Rows[0]["CALCULATIONBASE"].ToString().ToUpper() == "MRP") { intCalculation = 1; } else { intCalculation = 2; } row["DiscCalculationBase"] = intCalculation.ToString(); dtLineItems.Rows.Add(row); //Update session table Session["InvLineItem"] = dtLineItems; txtQtyCrates.Text = string.Empty; txtQtyBox.Text = string.Empty; txtLtr.Text = string.Empty; txtPrice.Text = string.Empty; lblHidden.Text = string.Empty; txtPack.Text = ""; txtMRP.Text = ""; txtStockQty.Text = ""; txtValue.Text = string.Empty; txtCrateQty.Text = ""; txtBoxqty.Text = ""; txtPCSQty.Text = ""; txtViewTotalBox.Text = ""; txtViewTotalPcs.Text = ""; txtBoxPcs.Text = ""; } } } catch (Exception ex) { string message = "alert('Error: " + ex.Message + " !');"; Msg.Columns.Add("Mssg"); Msg.Rows.Add(Msg.NewRow()["Mssg"] = message); ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); ErrorSignal.FromCurrentContext().Raise(ex); return Msg; } return dtLineItems; } private void AddColumnInDataTable() { DataColumn column = new DataColumn(); column.DataType = System.Type.GetType("System.Int32"); column.AutoIncrement = true; column.AutoIncrementSeed = 1; column.AutoIncrementStep = 1; column.ColumnName = "SNO"; //-----------------------------------------------------------// dtLineItems = new DataTable("LineItemTable"); dtLineItems.Columns.Add(column); // dtLineItems.Columns.Add("MaterialGroup", typeof(string)); dtLineItems.Columns.Add("Product_Code", typeof(string)); dtLineItems.Columns.Add("Line_No", typeof(decimal)); dtLineItems.Columns.Add("Product", typeof(string)); dtLineItems.Columns.Add("Pack", typeof(string)); // dtLineItems.Columns.Add("Mrp", typeof(string)); dtLineItems.Columns.Add("So_Qty", typeof(decimal)); dtLineItems.Columns.Add("Invoice_Qty", typeof(decimal)); dtLineItems.Columns.Add("Box_Qty", typeof(decimal)); dtLineItems.Columns.Add("Pcs_Qty", typeof(decimal)); dtLineItems.Columns.Add("BoxPcs", typeof(decimal)); //dtLineItems.Columns.Add("QtyCrates", typeof(decimal)); //dtLineItems.Columns.Add("QtyBox", typeof(int)); dtLineItems.Columns.Add("Ltr", typeof(decimal)); dtLineItems.Columns.Add("Rate", typeof(decimal)); dtLineItems.Columns.Add("BasePrice", typeof(decimal)); dtLineItems.Columns.Add("Amount", typeof(decimal)); //dtLineItems.Columns.Add("UOM", typeof(string)); /*-------Discount---------*/ dtLineItems.Columns.Add("DISCTYPE", typeof(string)); dtLineItems.Columns.Add("Disc", typeof(decimal)); dtLineItems.Columns.Add("DiscVal", typeof(decimal)); dtLineItems.Columns.Add("SchemeDisc", typeof(decimal)); dtLineItems.Columns.Add("SchemeDiscVal", typeof(decimal)); //===========Tax============================== dtLineItems.Columns.Add("TaxPer", typeof(decimal)); dtLineItems.Columns.Add("TaxValue", typeof(decimal)); dtLineItems.Columns.Add("AddTaxPer", typeof(decimal)); dtLineItems.Columns.Add("AddTaxValue", typeof(decimal)); dtLineItems.Columns.Add("MRP", typeof(decimal)); dtLineItems.Columns.Add("TaxableAmount", typeof(decimal)); dtLineItems.Columns.Add("StockQty", typeof(decimal)); //mrp or price dtLineItems.Columns.Add("SchemeCode", typeof(string)); dtLineItems.Columns.Add("Total", typeof(decimal)); dtLineItems.Columns.Add("TD", typeof(decimal)); dtLineItems.Columns.Add("SecDiscPer", typeof(decimal)); dtLineItems.Columns.Add("SecDiscAmount", typeof(decimal)); dtLineItems.Columns.Add("CALCULATIONBASE", typeof(string)); dtLineItems.Columns.Add("CalculationOn", typeof(string)); dtLineItems.Columns.Add("DiscCalculationBase", typeof(string)); // New Fields for GST dtLineItems.Columns.Add("HSNCode", typeof(string)); dtLineItems.Columns.Add("TaxComponent", typeof(string)); dtLineItems.Columns.Add("AddTaxComponent", typeof(string)); dtLineItems.Columns.Add("PE", typeof(decimal)); dtLineItems.Columns.Add("CLAIMDISCAMT", typeof(decimal)); dtLineItems.Columns.Add("TAX1", typeof(decimal)); dtLineItems.Columns.Add("TAX2", typeof(decimal)); dtLineItems.Columns.Add("TAX1COMPONENT", typeof(string)); dtLineItems.Columns.Add("TAX2COMPONENT", typeof(string)); } private void AddColumnInSchemeDataTable() { dtSchemeLineItems = new DataTable("SchemeLineItemTable"); dtSchemeLineItems.Columns.Add("Srno", typeof(int)); dtSchemeLineItems.Columns.Add("Avail", typeof(bool)); dtSchemeLineItems.Columns.Add("SchemeCode", typeof(string)); dtSchemeLineItems.Columns.Add("SchemeName", typeof(string)); dtSchemeLineItems.Columns.Add("ProductGroup", typeof(string)); dtSchemeLineItems.Columns.Add("ProductCode", typeof(string)); dtSchemeLineItems.Columns.Add("ProductName", typeof(string)); dtSchemeLineItems.Columns.Add("Slab", typeof(int)); dtSchemeLineItems.Columns.Add("Set", typeof(int)); dtSchemeLineItems.Columns.Add("FreeBoxQty", typeof(int)); dtSchemeLineItems.Columns.Add("AvailBoxQty", typeof(int)); dtSchemeLineItems.Columns.Add("FreePCSQty", typeof(int)); dtSchemeLineItems.Columns.Add("AvailPCSQty", typeof(int)); dtSchemeLineItems.Columns.Add("PackSize", typeof(int)); dtSchemeLineItems.Columns.Add("ConvQty", typeof(decimal)); dtSchemeLineItems.Columns.Add("Rate", typeof(decimal)); dtSchemeLineItems.Columns.Add("QtyLtr", typeof(decimal)); dtSchemeLineItems.Columns.Add("Price", typeof(decimal)); dtSchemeLineItems.Columns.Add("Value", typeof(decimal)); dtSchemeLineItems.Columns.Add("UOM", typeof(string)); //===========Discount========================= dtSchemeLineItems.Columns.Add("DiscType", typeof(string)); dtSchemeLineItems.Columns.Add("Disc", typeof(decimal)); dtSchemeLineItems.Columns.Add("DiscVal", typeof(decimal)); dtSchemeLineItems.Columns.Add("SchemeDisc", typeof(decimal)); dtSchemeLineItems.Columns.Add("SchemeDiscVal", typeof(decimal)); //===========Tax============================== dtSchemeLineItems.Columns.Add("Tax_Code", typeof(decimal)); dtSchemeLineItems.Columns.Add("Tax_Amount", typeof(decimal)); dtSchemeLineItems.Columns.Add("AddTax_Code", typeof(decimal)); dtSchemeLineItems.Columns.Add("AddTax_Amount", typeof(decimal)); dtSchemeLineItems.Columns.Add("MRP", typeof(decimal)); dtSchemeLineItems.Columns.Add("CalculationBase", typeof(string)); dtSchemeLineItems.Columns.Add("Calculationon", typeof(string)); //mrp or price dtSchemeLineItems.Columns.Add("TaxableAmount", typeof(decimal)); // New Fields for GST dtSchemeLineItems.Columns.Add("HSNCode", typeof(string)); dtSchemeLineItems.Columns.Add("TaxComponent", typeof(string)); dtSchemeLineItems.Columns.Add("AddTaxComponent", typeof(string)); dtSchemeLineItems.Columns.Add("CLAIMDISCAMT", typeof(decimal)); dtSchemeLineItems.Columns.Add("TAX1", typeof(decimal)); dtSchemeLineItems.Columns.Add("TAX2", typeof(decimal)); dtSchemeLineItems.Columns.Add("TAX1COMPONENT", typeof(string)); dtSchemeLineItems.Columns.Add("TAX2COMPONENT", typeof(string)); } protected void btnGO_Click(object sender, EventArgs e) { try { decimal SecDiscPer = 0, SecDiscValue = 0, SchemeDiscVal = 0; if (string.IsNullOrEmpty(txtSecDiscPer.Text)) { txtSecDiscPer.Text = "0"; } if (string.IsNullOrEmpty(txtSecDiscValue.Text)) { txtSecDiscValue.Text = "0"; } DataTable dt = (DataTable)Session["InvLineItem"]; dt.Columns["SecDiscPer"].ReadOnly = false; dt.Columns["SecDiscAmount"].ReadOnly = false; dt.Columns["TaxValue"].ReadOnly = false; dt.Columns["AddTaxValue"].ReadOnly = false; dt.Columns["TaxableAmount"].ReadOnly = false; dt.Columns["Total"].ReadOnly = false; //dt.Rows[i]["TaxValue"] = taxvalue.Text; //dt.Rows[i]["AddTaxValue"] = AddTaxVal.Text; //dt.Rows[i]["TaxableAmount"] = hdnTaxableammount.Value; //dt.Rows[i]["Total"] = NetAmount.ToString("0.00"); //foreach (GridViewRow gv in gvDetails.Rows) for (int i = 0; gvDetails.Rows.Count > i; i++) { HiddenField discType = (HiddenField)gvDetails.Rows[i].FindControl("hDiscType"); HiddenField discCalculation = (HiddenField)gvDetails.Rows[i].FindControl("hDiscCalculationType"); Label lblMRP = (Label)gvDetails.Rows[i].FindControl("MRP"); HiddenField ProductCode = (HiddenField)gvDetails.Rows[i].FindControl("HiddenField2"); SecDiscPer = Convert.ToDecimal(txtSecDiscPer.Text); SecDiscValue = Convert.ToDecimal(txtSecDiscValue.Text); TextBox Invoice_Qty = (TextBox)gvDetails.Rows[i].FindControl("txtBox"); TextBox txtRate = (TextBox)gvDetails.Rows[i].FindControl("txtRate"); Label DiscPer = (Label)gvDetails.Rows[i].FindControl("Disc"); Label DiscVal = (Label)gvDetails.Rows[i].FindControl("DiscValue"); Label tax = (Label)gvDetails.Rows[i].FindControl("Tax"); Label taxvalue = (Label)gvDetails.Rows[i].FindControl("TaxValue"); Label AddtaxPer = (Label)gvDetails.Rows[i].FindControl("AddTax"); Label AddTaxVal = (Label)gvDetails.Rows[i].FindControl("AddTaxValue"); Label netamount = (Label)gvDetails.Rows[i].FindControl("Amount"); TextBox SDiscPer = (TextBox)gvDetails.Rows[i].FindControl("SecDisc"); TextBox SDiscVal = (TextBox)gvDetails.Rows[i].FindControl("SecDiscValue"); Label lblSchemeDiscVal = (Label)gvDetails.Rows[i].FindControl("lblSchemeDiscVal"); if (lblSchemeDiscVal.Text.Trim().Length > 0) { SchemeDiscVal = Convert.ToDecimal(lblSchemeDiscVal.Text); } Label lblTotal = (Label)gvDetails.Rows[i].FindControl("Total"); HiddenField hdnTaxableammount = (HiddenField)gvDetails.Rows[i].FindControl("hdnTaxableAmount"); decimal Basic = Convert.ToDecimal(Invoice_Qty.Text) * Convert.ToDecimal(txtRate.Text); if (SecDiscPer != 0) { SecDiscValue = (SecDiscPer * Basic) / 100; } decimal LineAmount = Basic - (SecDiscValue + (SchemeDiscVal) + Convert.ToDecimal(DiscVal.Text)); decimal TaxValue = (LineAmount * Convert.ToDecimal(tax.Text)) / 100; decimal AddTaxValue = 0;// (LineAmount * Convert.ToDecimal(AddtaxPer.Text)) / 100; DataTable dtTax = new DataTable(); string s = ProductCode.Value; /*----------GST Implement-----------------*/ //if (txtBillToState.Text == "JK") //{ // dtTax = baseObj.GetData("Select H.TaxValue,H.ACXADDITIONALTAXVALUE,H.ACXADDITIONALTAXBASIS from [ax].inventsite G inner join InventTax H on G.TaxGroup=H.TaxGroup where H.ItemId='" + ProductCode.Value + "' and G.Siteid='" + Session["SiteCode"].ToString() + "'"); // if (dtTax.Rows.Count > 0) // { // if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 0) // Tax On Tax // { // AddTaxValue = (TaxValue * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // else if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 1) // Tax On Taxable Amount // { // AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // else // { // AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // } //} //else //{ AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); ////} decimal NetAmount = LineAmount + TaxValue + AddTaxValue; if (NetAmount > 0) { hdnTaxableammount.Value = LineAmount.ToString("0.00"); taxvalue.Text = TaxValue.ToString("0.00"); AddTaxVal.Text = AddTaxValue.ToString("0.00"); SDiscPer.Text = SecDiscPer.ToString("0.00"); SDiscVal.Text = SecDiscValue.ToString("0.00"); // Sec Discount Value dt.Rows[i]["SecDiscPer"] = SDiscPer.Text; dt.Rows[i]["SecDiscAmount"] = SDiscVal.Text; dt.Rows[i]["TaxValue"] = taxvalue.Text; dt.Rows[i]["AddTaxValue"] = AddTaxVal.Text; dt.Rows[i]["TaxableAmount"] = hdnTaxableammount.Value; dt.Rows[i]["Total"] = NetAmount.ToString("0.00"); netamount.Text = NetAmount.ToString("0.00"); lblTotal.Text = NetAmount.ToString("0.00"); } else { if (Basic > 0) { txtSecDiscValue.Text = "0.00"; txtSecDiscPer.Text = "0.00"; string message = "alert('Invoice Line value should not be less than zero!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } } if (txtTDValue.Text != "") { TDCalculation(); } GrandTotal(); UpdateSession(); DataTable dtApplicable = baseObj.GetData("SELECT APPLICABLESCHEMEDISCOUNT from AX.ACXCUSTMASTER WHERE CUSTOMER_CODE = '" + drpCustomerCode.SelectedValue.ToString() + "'"); if (dtApplicable.Rows.Count > 0) { intApplicable = Convert.ToInt32(dtApplicable.Rows[0]["APPLICABLESCHEMEDISCOUNT"].ToString()); } if (intApplicable == 1 || intApplicable == 3) { foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkgrd = (CheckBox)rw.FindControl("chkSelect"); TextBox txtQty = (TextBox)rw.FindControl("txtQty"); TextBox txtQtyPCS = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Text = ""; txtQtyPCS.Text = ""; chkgrd.Checked = false; } this.SchemeDiscCalculation(); BindSchemeGrid(); this.SchemeDiscCalculation(); DataTable dt1 = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt1 = (DataTable)Session["InvLineItem"]; } GridViewFooterCalculate(dt1); } //btnApply_Click(sender, e); } //dt = (DataTable)Session["InvLineItem"]; //Session["InvLineItem"] = dt; //DataTable dt = new DataTable(); Upnel.Update(); } catch(Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } finally { } } protected void txtSecDiscPer_TextChanged(object sender, EventArgs e) { if (txtSecDiscValue.Text != string.Empty) { txtSecDiscValue.Text = string.Empty; btnGO.Focus(); } } protected void txtSecDiscValue_TextChanged(object sender, EventArgs e) { if (txtSecDiscPer.Text != string.Empty) { txtSecDiscPer.Text = string.Empty; btnGO.Focus(); } } protected void SecCalculation() { // decimal SecDiscPer = 0, SecDiscValue = 0; } protected void SecDisc_TextChanged(object sender, EventArgs e) { decimal SecDiscPer = 0, SecDiscValue = 0, SchemeDiscVal = 0; TextBox SDiscPer = (TextBox)sender; GridViewRow gv = (GridViewRow)SDiscPer.Parent.Parent; if (string.IsNullOrEmpty(SDiscPer.Text)) { SDiscPer.Text = "0"; } SecDiscPer = Convert.ToDecimal(SDiscPer.Text); int idx = gv.RowIndex; HiddenField discType = (HiddenField)gv.FindControl("hDiscType"); HiddenField discCalculation = (HiddenField)gv.FindControl("hDiscCalculationType"); Label lblMRP = (Label)gv.FindControl("MRP"); HiddenField ProductCode = (HiddenField)gv.FindControl("HiddenField2"); TextBox Invoice_Qty = (TextBox)gv.FindControl("txtBox"); TextBox txtRate = (TextBox)gv.FindControl("txtRate"); Label DiscPer = (Label)gv.FindControl("Disc"); Label DiscVal = (Label)gv.FindControl("DiscValue"); Label tax = (Label)gv.FindControl("Tax"); Label taxvalue = (Label)gv.FindControl("TaxValue"); Label AddtaxPer = (Label)gv.FindControl("AddTax"); Label AddTaxVal = (Label)gv.FindControl("AddTaxValue"); Label netamount = (Label)gv.FindControl("Amount"); TextBox SDiscVal = (TextBox)gv.FindControl("SecDiscValue"); Label lblSchemeDiscVal = (Label)gv.FindControl("lblSchemeDiscVal"); if (lblSchemeDiscVal.Text.Trim().Length > 0) { SchemeDiscVal = Convert.ToDecimal(lblSchemeDiscVal.Text); } Label lblTotal = (Label)gv.FindControl("Total"); boolDiscAvalMRP = false; HiddenField hdnTaxableammount = (HiddenField)gv.FindControl("hdnTaxableAmount"); decimal Basic = Convert.ToDecimal(Invoice_Qty.Text) * Convert.ToDecimal(txtRate.Text); if (SecDiscPer != 0) { SecDiscValue = (SecDiscPer * Basic) / 100; } //============================== decimal LineAmount = Basic - (SecDiscValue + (SchemeDiscVal) + Convert.ToDecimal(DiscVal.Text)); decimal TaxValue = (LineAmount * Convert.ToDecimal(tax.Text)) / 100; hdnTaxableammount.Value = LineAmount.ToString(); decimal AddTaxValue = 0; DataTable dtTax = new DataTable(); /*----------------GST IMPLEMENTATION-------------------*/ //if (txtBillToState.Text == "JK") //{ // dtTax = baseObj.GetData("Select H.TaxValue,H.ACXADDITIONALTAXVALUE,H.ACXADDITIONALTAXBASIS from [ax].inventsite G inner join InventTax H on G.TaxGroup=H.TaxGroup where H.ItemId='" + ProductCode.Value + "' and G.Siteid='" + Session["SiteCode"].ToString() + "'"); // if (dtTax.Rows.Count > 0) // { // if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 0) // Tax On Tax // { // AddTaxValue = (TaxValue * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // else if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 1) // Tax On Taxable Amount // { // AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // else // { // AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); // } // } //} //else //{ AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); //} // (LineAmount * Convert.ToDecimal(AddTaxVal.Text)) / 100; decimal NetAmount = LineAmount + TaxValue + AddTaxValue; if (NetAmount > 0) { taxvalue.Text = TaxValue.ToString("0.00"); AddTaxVal.Text = AddTaxValue.ToString("0.00"); SDiscPer.Text = SecDiscPer.ToString("0.00"); SDiscVal.Text = SecDiscValue.ToString("0.00"); netamount.Text = NetAmount.ToString("0.00"); lblTotal.Text = NetAmount.ToString("0.00"); } else { if (Basic > 0) { SDiscPer.Text = "0.00"; SDiscVal.Text = "0.00"; SecDiscValue_TextChanged(sender, e); string message = "alert('Invoice Line Value should not be less than zero!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } } if (txtTDValue.Text != "") { TDCalculation(); } GrandTotal(); UpdateSession(); } protected void SecDiscValue_TextChanged(object sender, EventArgs e) { decimal SecDiscPer = 0, SecDiscValue = 0, SchemeDiscVal = 0; TextBox SDiscVal = (TextBox)sender; GridViewRow gv = (GridViewRow)SDiscVal.Parent.Parent; if (string.IsNullOrEmpty(SDiscVal.Text)) { SDiscVal.Text = "0"; } SecDiscValue = Convert.ToDecimal(SDiscVal.Text); int idx = gv.RowIndex; HiddenField discType = (HiddenField)gv.FindControl("hDiscType"); HiddenField discCalculation = (HiddenField)gv.FindControl("hDiscCalculationType"); Label lblMRP = (Label)gv.FindControl("MRP"); HiddenField ProductCode = (HiddenField)gv.FindControl("HiddenField2"); TextBox Invoice_Qty = (TextBox)gv.FindControl("txtBox"); TextBox txtRate = (TextBox)gv.FindControl("txtRate"); Label DiscPer = (Label)gv.FindControl("Disc"); Label DiscVal = (Label)gv.FindControl("DiscValue"); Label tax = (Label)gv.FindControl("Tax"); Label taxvalue = (Label)gv.FindControl("TaxValue"); Label AddtaxPer = (Label)gv.FindControl("AddTax"); Label AddTaxVal = (Label)gv.FindControl("AddTaxValue"); Label netamount = (Label)gv.FindControl("Amount"); TextBox SDiscPer = (TextBox)gv.FindControl("SecDisc"); Label lblSchemeDiscVal = (Label)gv.FindControl("lblSchemeDiscVal"); if (lblSchemeDiscVal.Text.Trim().Length > 0) { SchemeDiscVal = Convert.ToDecimal(lblSchemeDiscVal.Text); } Label lblTotal = (Label)gv.FindControl("Total"); decimal Basic = Convert.ToDecimal(Invoice_Qty.Text) * Convert.ToDecimal(txtRate.Text); decimal LineAmount = Basic - (SecDiscValue + (SchemeDiscVal) + Convert.ToDecimal(DiscVal.Text)); HiddenField hdnTaxableammount = (HiddenField)gv.FindControl("hdnTaxableAmount"); hdnTaxableammount.Value = LineAmount.ToString(); decimal TaxValue = (LineAmount * Convert.ToDecimal(tax.Text)) / 100; decimal AddTaxValue = 0; //if (txtBillToState.Text == "JK") //{ DataTable dtTax = new DataTable(); //// dtTax = baseObj.GetData("Select H.TaxValue,H.ACXADDITIONALTAXVALUE,H.ACXADDITIONALTAXBASIS from [ax].inventsite G inner join InventTax H on G.TaxGroup=H.TaxGroup where H.ItemId='" + ProductCode.Value + "' and G.Siteid='" + Session["SiteCode"].ToString() + "'"); //// if (dtTax.Rows.Count > 0) //// { //// if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 0) // Tax On Tax //// { //// AddTaxValue = (TaxValue * (Convert.ToDecimal(AddtaxPer.Text) / 100)); //// } //// else if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 1) // Tax On Taxable Amount //// { //// AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); //// } //// else //// { //// AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); //// } //// } ////} ////else ////{ AddTaxValue = (LineAmount * (Convert.ToDecimal(AddtaxPer.Text) / 100)); //} decimal NetAmount = (LineAmount + TaxValue + AddTaxValue); if (NetAmount > 0) { taxvalue.Text = TaxValue.ToString("0.00"); AddTaxVal.Text = AddTaxValue.ToString("0.00"); SDiscPer.Text = SecDiscPer.ToString("0.00"); SDiscVal.Text = SecDiscValue.ToString("0.00"); netamount.Text = NetAmount.ToString("0.00"); lblTotal.Text = NetAmount.ToString("0.00"); } else { if (Basic > 0) { SDiscVal.Text = "0.00"; string message = "alert('Invoice Line Value should not be less than zero!!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } } if (txtTDValue.Text != "") { TDCalculation(); } GrandTotal(); UpdateSession(); } protected void txtTDValue_TextChanged(object sender, EventArgs e) { } protected void btnApply_Click(object sender, EventArgs e) { // btnGO_Click(sender,e); if (txtTDValue.Text == "") { txtTDValue.Text = "0"; } if (txtTDValue.Text != "") { TDCalculation(); GrandTotal(); UpdateSession(); DataTable dtApplicable = baseObj.GetData("SELECT APPLICABLESCHEMEDISCOUNT from AX.ACXCUSTMASTER WHERE CUSTOMER_CODE = '" + drpCustomerCode.SelectedValue.ToString() + "'"); if (dtApplicable.Rows.Count > 0) { intApplicable = Convert.ToInt32(dtApplicable.Rows[0]["APPLICABLESCHEMEDISCOUNT"].ToString()); } if (intApplicable == 1 || intApplicable == 3) { foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkgrd = (CheckBox)rw.FindControl("chkSelect"); TextBox txtQty = (TextBox)rw.FindControl("txtQty"); TextBox txtQtyPCS = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Text = ""; txtQtyPCS.Text = ""; chkgrd.Checked = false; } this.SchemeDiscCalculation(); BindSchemeGrid(); this.SchemeDiscCalculation(); DataTable dt1 = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt1 = (DataTable)Session["InvLineItem"]; } GridViewFooterCalculate(dt1); } } else { } } public void TDCalculation() { try { decimal totalBasicValue = 0, SchemeDiscVal = 0; //=========For calculate TD % ================ foreach (GridViewRow gv in gvDetails.Rows) { TextBox Invoice_Qty = (TextBox)gv.FindControl("txtBox"); TextBox txtRate = (TextBox)gv.FindControl("txtRate"); HiddenField ProductCode = (HiddenField)gv.FindControl("HiddenField2"); HiddenField discType = (HiddenField)gv.FindControl("hDiscType"); HiddenField discCalculation = (HiddenField)gv.FindControl("hDiscCalculationType"); Label lblMRP = (Label)gv.FindControl("MRP"); totalBasicValue = totalBasicValue + (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(Invoice_Qty.Text)); //totalBasicValue = totalBasicValue + (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(Invoice_Qty.Text)); } decimal TDPercentage = Convert.ToDecimal(txtTDValue.Text) / totalBasicValue; //=================Apply TD Percentage================= foreach (GridViewRow gv in gvDetails.Rows) { HiddenField discType = (HiddenField)gv.FindControl("hDiscType"); HiddenField discCalculation = (HiddenField)gv.FindControl("hDiscCalculationType"); Label lblMRP = (Label)gv.FindControl("MRP"); HiddenField ProductCode = (HiddenField)gv.FindControl("HiddenField2"); TextBox Invoice_Qty = (TextBox)gv.FindControl("txtBox"); TextBox txtRate = (TextBox)gv.FindControl("txtRate"); Label tax = (Label)gv.FindControl("Tax"); decimal TaxPer = Convert.ToDecimal(tax.Text); Label DiscVal = (Label)gv.FindControl("DiscValue"); TextBox txtSecDiscVal = (TextBox)gv.FindControl("SecDiscValue"); Label lblTD = (Label)gv.FindControl("TD"); Label lblPE = (Label)gv.FindControl("PE"); Label lblTotal = (Label)gv.FindControl("Total"); Label lblToatlBeforeTax = (Label)gv.FindControl("ToatlBeforeTax"); Label lblVatAfterPE = (Label)gv.FindControl("VatAfterPE"); Label lblSchemeDiscVal = (Label)gv.FindControl("lblSchemeDiscVal"); Label taxValue = (Label)gv.FindControl("TaxValue"); Label addTaxValue = (Label)gv.FindControl("AddTaxValue"); if (lblSchemeDiscVal.Text.Trim().Length > 0) { SchemeDiscVal = Convert.ToDecimal(lblSchemeDiscVal.Text); } HiddenField hdnTaxableammount = (HiddenField)gv.FindControl("hdnTaxableAmount"); Label Addtax = (Label)gv.FindControl("AddTax"); decimal AddTaxPer = Convert.ToDecimal(Addtax.Text); if (txtSecDiscVal.Text == string.Empty) { txtSecDiscVal.Text = "0"; } if (Convert.ToDecimal(Invoice_Qty.Text) > 0) { decimal BasicValue = (Convert.ToDecimal(txtRate.Text) * Convert.ToDecimal(Invoice_Qty.Text)); decimal TD = (BasicValue * TDPercentage); lblTD.Text = TD.ToString("0.0000"); decimal PE = 0;// TD * (((TaxPer + AddTaxPer) / 100) / (1 + ((TaxPer + AddTaxPer) / 100))); DataTable dtTax = new DataTable(); dtTax = baseObj.GetData("Select H.TaxValue,H.ACXADDITIONALTAXVALUE,H.ACXADDITIONALTAXBASIS from [ax].inventsite G inner join InventTax H on G.TaxGroup=H.TaxGroup where H.ItemId='" + ProductCode.Value + "' and G.Siteid='" + Session["SiteCode"].ToString() + "'"); //if (txtBillToState.Text == "JK") //{ // if (dtTax.Rows.Count > 0) // { // if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 0) // Tax On Tax // { // PE = TD * (((TaxPer + TaxPer * AddTaxPer / 100) / 100) / (1 + ((TaxPer + TaxPer * AddTaxPer / 100) / 100))); // } // else // Tax On Taxable Amount (ACXADDITIONALTAXBASIS=1 or 2) // { // PE = TD * (((TaxPer + AddTaxPer) / 100) / (1 + ((TaxPer + AddTaxPer) / 100))); // } // } //} //else //{ PE = TD * (((TaxPer + AddTaxPer) / 100) / (1 + ((TaxPer + AddTaxPer) / 100))); ////} lblPE.Text = PE.ToString("0.00"); decimal BeforeTaxTotal = BasicValue - SchemeDiscVal - Convert.ToDecimal(DiscVal.Text) - Convert.ToDecimal(txtSecDiscVal.Text) - TD + PE; hdnTaxableammount.Value = BeforeTaxTotal.ToString(); lblToatlBeforeTax.Text = BeforeTaxTotal.ToString("0.00"); taxValue.Text = Convert.ToDecimal((BeforeTaxTotal * TaxPer) / 100).ToString("0.00"); addTaxValue.Text = Convert.ToDecimal((BeforeTaxTotal * AddTaxPer) / 100).ToString("0.00"); decimal VatAfterPE = 0;// BeforeTaxTotal * (TaxPer + AddTaxPer) / 100; //if (txtBillToState.Text == "JK") //{ // if (dtTax.Rows.Count > 0) // { // if (Convert.ToInt16(dtTax.Rows[0]["ACXADDITIONALTAXBASIS"].ToString()) == 0) // Tax On Tax // { // VatAfterPE = BeforeTaxTotal * (TaxPer + TaxPer * AddTaxPer / 100) / 100; // } // else // Tax On Taxable Amount (ACXADDITIONALTAXBASIS=1 or 2) // { // VatAfterPE = BeforeTaxTotal * (TaxPer + AddTaxPer) / 100; // } // } //} //else //{ VatAfterPE = BeforeTaxTotal * (TaxPer + AddTaxPer) / 100; ////} lblVatAfterPE.Text = VatAfterPE.ToString("0.0000"); decimal total = BeforeTaxTotal + VatAfterPE; lblTotal.Text = total.ToString("0.0000"); if (Convert.ToDecimal(txtTDValue.Text) == 0 || txtTDValue.Text == string.Empty) { lblToatlBeforeTax.Text = "0.0000"; lblVatAfterPE.Text = "0.0000"; } } else { lblTD.Text = "0.00"; lblPE.Text = "0.00"; lblToatlBeforeTax.Text = "0.00"; lblVatAfterPE.Text = "0.00"; lblTotal.Text = "0.00"; } } //Also Update session } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } finally { } } protected void drpCustomerGroup_SelectedIndexChanged(object sender, EventArgs e) { } public void FillProductCode() { DDLMaterialCode.Items.Clear(); // DDLMaterialCode.Items.Add("Select..."); if (DDLProductGroup.Text == "Select..." && DDLProductSubCategory.Text == "Select..." || DDLProductSubCategory.Text == "") { strQuery = "select distinct(ItemId) as Product_Code,concat([ITEMID],' - ',Product_Name) as Product_Name from ax.INVENTTABLE WHERE BLOCK=0 order by Product_Name"; DDLMaterialCode.Items.Clear(); DDLMaterialCode.Items.Add("Select..."); baseObj.BindToDropDown(DDLMaterialCode, strQuery, "Product_Name", "Product_Code"); DDLMaterialCode.Focus(); } } private void CalculateInvoiceValue() { DataTable dtsum = new DataTable(); decimal TotalInvValue = 0; if (Session["InvLineItem"] != null) { dtsum = (DataTable)Session["InvLineItem"]; TotalInvValue = Convert.ToDecimal(dtsum.Compute("Sum(total)", "")); } foreach (GridViewRow rw in gvScheme.Rows) { { TotalInvValue += Convert.ToDecimal(rw.Cells[24].Text); } } txtinvoicevalue.Text = TotalInvValue.ToString("0.00"); } protected void UpdateSession() { decimal SchemeDiscVal = 0; foreach (GridViewRow row in gvDetails.Rows) { HiddenField hdnTaxableAmount = (HiddenField)row.Cells[0].FindControl("hdnTaxableAmount"); HiddenField hdfLineNo = (HiddenField)row.Cells[0].FindControl("hdfLineNo"); HiddenField hClaimDiscAmt = (HiddenField)row.FindControl("hClaimDiscAmt"); Label lblSOQty = (Label)row.Cells[0].FindControl("SO_Qty"); TextBox txtBox = (TextBox)row.Cells[0].FindControl("txtBox"); Label lblStockQty = (Label)row.Cells[0].FindControl("StockQty"); Label lblLtr = (Label)row.Cells[0].FindControl("Ltr"); TextBox txtRate = (TextBox)row.FindControl("txtRate"); Label tax = (Label)row.FindControl("Tax"); Label taxvalue = (Label)row.FindControl("TaxValue"); Label AddtaxPer = (Label)row.FindControl("AddTax"); Label AddTaxValue = (Label)row.FindControl("AddTaxValue"); Label DiscPer = (Label)row.FindControl("Disc"); Label DiscVal = (Label)row.FindControl("DiscValue"); TextBox SDiscPer = (TextBox)row.FindControl("SecDisc"); TextBox SDiscVal = (TextBox)row.FindControl("SecDiscValue"); Label amount = (Label)row.FindControl("Amount"); Label lblTotal = (Label)row.FindControl("Total"); TextBox txtBoxQtyGrid = (TextBox)row.FindControl("txtBoxQtyGrid"); TextBox txtPcsQtyGrid = (TextBox)row.FindControl("txtPcsQtyGrid"); Label txtBoxPcs = (Label)row.FindControl("txtBoxPcs"); Label tdAmount = (Label)row.FindControl("TD"); Label peAmount = (Label)row.FindControl("PE"); if (peAmount.Text.Trim().Length == 0) { peAmount.Text = "0.00"; } Label lblSchemeDiscVal = (Label)row.FindControl("lblSchemeDiscVal"); if (lblSchemeDiscVal.Text.Trim().Length > 0) { SchemeDiscVal = Convert.ToDecimal(lblSchemeDiscVal.Text); } decimal SecDiscPer = Convert.ToDecimal(SDiscPer.Text); decimal SecDiscValue = Convert.ToDecimal(SDiscVal.Text); dtLineItems = (DataTable)Session["InvLineItem"]; foreach (DataColumn DC in dtLineItems.Columns) { DC.ReadOnly = false; } dtLineItems.Select(string.Format("[Line_No] = '{0}'", hdfLineNo.Value.ToString())) .ToList<DataRow>() .ForEach(r => { r["So_Qty"] = lblSOQty.Text; r["Invoice_Qty"] = txtBox.Text; r["Box_Qty"] = txtBoxQtyGrid.Text; r["Pcs_Qty"] = txtPcsQtyGrid.Text; r["BoxPcs"] = txtBoxPcs.Text; r["StockQty"] = lblStockQty.Text; r["Ltr"] = lblLtr.Text; r["Rate"] = txtRate.Text; r["DiscVal"] = DiscVal.Text; r["Amount"] = amount.Text; r["TaxValue"] = taxvalue.Text; r["ADDTaxValue"] = AddTaxValue.Text; r["TaxableAmount"] = hdnTaxableAmount.Value.ToString(); r["Total"] = lblTotal.Text; r["SecDiscPer"] = SDiscPer.Text; r["SecDiscAmount"] = SDiscVal.Text; r["SchemeDiscVal"] = SchemeDiscVal; r["TD"] = tdAmount.Text; r["PE"] = peAmount.Text; r["ClaimDiscAmt"] = hClaimDiscAmt.Value; }); } CalculateInvoiceValue(); } protected void txtLtr_TextChanged(object sender, EventArgs e) { } protected void txtCrateQty_TextChanged(object sender, EventArgs e) { CalculateQtyAmt(sender); } protected void txtBoxqty_TextChanged(object sender, EventArgs e) { CalculateQtyAmt(sender); } protected void txtPCSQty_TextChanged(object sender, EventArgs e) { CalculateQtyAmt(sender); } public void CalculateQtyAmt(Object sender) { decimal dblTotalQty = 0, crateQty = 0, boxQty = 0, pcsQty = 0, crateSize = 0, boxPackSize = 0; crateQty = Global.ParseDecimal(txtCrateQty.Text); boxQty = Global.ParseDecimal(txtBoxqty.Text); pcsQty = Global.ParseDecimal(txtPCSQty.Text); crateSize = Global.ParseDecimal(txtCrateSize.Text); boxPackSize = Global.ParseDecimal(txtPack.Text); txtCrateQty.Text = Convert.ToString(crateQty); txtBoxqty.Text = Convert.ToString(boxQty); txtPCSQty.Text = Convert.ToString(pcsQty); dblTotalQty = crateQty * crateSize + boxQty + (pcsQty / (boxPackSize == 0 ? 1 : boxPackSize)); //Total qty (Create+box+pcs) with decimal factor //txtEnterQty.Text = dblTotalQty.ToString("0.00"); //Total Qty txtQtyBox.Text = dblTotalQty.ToString("0.000000"); // txtEnterQty.Text; //Total Qty txtStockQty.Text = (txtStockQty.Text.Trim().Length == 0 ? "0" : txtStockQty.Text); decimal TotalBox = 0, TotalPcs = 0; TotalBox = Math.Truncate(dblTotalQty); //Extract Only Box Qty From Total Qty TotalPcs = Math.Round((dblTotalQty - TotalBox) * boxPackSize); //Extract Only Pcs Qty From Total Qty string BoxPcs = Convert.ToString(TotalBox) + '.' + (Convert.ToString(TotalPcs).Length == 1 ? "0" : "") + Convert.ToString(TotalPcs); // Call CalculatePrice txtStockQty.Text = (txtStockQty.Text.Trim().Length == 0 ? "0" : txtStockQty.Text); txtQtyBox.Text = (txtQtyBox.Text.Trim().Length == 0 ? "0" : txtQtyBox.Text); try { string[] calValue = baseObj.CalculatePrice1(DDLMaterialCode.SelectedItem.Value, drpCustomerCode.SelectedItem.Value, dblTotalQty, "Box"); if (calValue[0] != "") { if (calValue[5] == "Box") { txtBoxPcs.Text = BoxPcs; txtViewTotalBox.Text = TotalBox.ToString("0.00"); txtViewTotalPcs.Text = TotalPcs.ToString("0.00"); // txtQtyBox.Text = txtEnterQty.Text; txtQtyCrates.Text = calValue[0]; if (Convert.ToDecimal(txtQtyBox.Text) > Convert.ToDecimal(txtStockQty.Text)) { string message = "alert('Stock not available !!');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } txtLtr.Text = calValue[1]; txtPrice.Text = calValue[2]; txtValue.Text = calValue[3]; lblHidden.Text = calValue[4]; BtnAddItem.Focus(); BtnAddItem.CausesValidation = false; } else { lblMessage.Text = "Price Not Define !"; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); string message = "alert('" + ex.Message.ToString() + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); } } protected void txtBoxQtyGrid_TextChanged(object sender, EventArgs e) { CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); TextBox txtBoxQty = (TextBox)sender; GridViewRow row = (GridViewRow)txtBoxQty.Parent.Parent; HiddenField ddlPrCode = (HiddenField)row.Cells[0].FindControl("HiddenField2"); TextBox txtPcs = (TextBox)row.Cells[0].FindControl("txtPcsQtyGrid"); TextBox textTotal = (TextBox)row.Cells[0].FindControl("txtBox"); if(txtBoxQty.Text=="") { txtBoxQty.Text = "0"; } decimal TotalBox; TotalBox = obj.GetTotalBox(ddlPrCode.Value, 0, Convert.ToDecimal(txtPcs.Text), Convert.ToDecimal(txtBoxQty.Text)); textTotal.Text = Convert.ToString(TotalBox); //if (dtLineItems != null && dtLineItems.Rows.Count > 0) //{ // DataRow[] dr = dtLineItems.Select("Line_No=" + hdfLineNo.Value.ToString()); //} txtBox_TextChanged((object)textTotal, e); } protected void txtPcsQtyGrid_TextChanged(object sender, EventArgs e) { CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); TextBox txtPcsQty = (TextBox)sender; GridViewRow row = (GridViewRow)txtPcsQty.Parent.Parent; HiddenField ddlPrCode = (HiddenField)row.Cells[0].FindControl("HiddenField2"); TextBox txtBoxQty = (TextBox)row.Cells[0].FindControl("txtBoxQtyGrid"); TextBox textTotal = (TextBox)row.Cells[0].FindControl("txtBox"); decimal TotalBox; TotalBox = obj.GetTotalBox(ddlPrCode.Value, 0, Convert.ToDecimal(txtPcsQty.Text), Convert.ToDecimal(txtBoxQty.Text)); textTotal.Text = Convert.ToString(TotalBox); txtBox_TextChanged((object)textTotal, e); } protected void GridLevelCalculation() { } public void PcsBillingApplicable() { DataTable dt = baseObj.GetPcsBillingApplicability(Session["SCHSTATE"].ToString(), DDLProductGroup.SelectedItem.Value); //st.Substring(st.Length - 6) + System.DateTime.Now.ToString("yyMMddhhmmss"); string ProductGroupApplicable = string.Empty; if (dt.Rows.Count > 0) { ProductGroupApplicable = dt.Rows[0][1].ToString(); } if (ProductGroupApplicable == "Y") { txtPCSQty.Enabled = true; } else { txtPCSQty.Enabled = false; } } protected Int32 getBoxPcsPicQty(string SchemeCode, int slab, string BoxPcs) { Int16 TotalQty = 0; foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); TextBox txtQtyPcs = (TextBox)rw.FindControl("txtQtyPcs"); TextBox txtQty = (TextBox)rw.FindControl("txtQty"); if (txtQty.Text.Trim().Length == 0) { txtQty.Text = "0"; } if (txtQtyPcs.Text.Trim().Length == 0) { txtQtyPcs.Text = "0"; } if (chkBx.Checked == true) { if (rw.Cells[1].Text == SchemeCode && Convert.ToInt16(rw.Cells[7].Text) == 0) { if (BoxPcs == "B") { TotalQty += Convert.ToInt16(txtQty.Text); } else { TotalQty += Convert.ToInt16(txtQtyPcs.Text); } } } } return TotalQty; } protected void txtQtyPcs_TextChanged(object sender, EventArgs e) { int TotalQtyPcs = 0; GridViewRow row = (GridViewRow)(((TextBox)sender)).NamingContainer; string SchemeCode = row.Cells[1].Text; int AvlFreeQtyPcs = Convert.ToInt16(row.Cells[11].Text); int Slab = Convert.ToInt16(row.Cells[6].Text); CheckBox chkBx1 = (CheckBox)row.FindControl("chkSelect"); TextBox txtQtyPcs1 = (TextBox)row.FindControl("txtQtyPcs"); foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); TextBox txtQtyPcs = (TextBox)rw.FindControl("txtQtyPcs"); if (chkBx.Checked == true) { //For Pcs if (!string.IsNullOrEmpty(txtQtyPcs.Text) && rw.Cells[1].Text == SchemeCode && Convert.ToInt16(rw.Cells[6].Text) == Slab) { TotalQtyPcs += Convert.ToInt16(txtQtyPcs.Text); if (getBoxPcsPicQty(SchemeCode, Slab, "B") > 0) { txtQtyPcs1.Text = "0"; chkBx1.Checked = false; txtQtyPcs1.ReadOnly = false; string message = "alert('Free Qty Pcs should not greater than available free qty pcs !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } if (TotalQtyPcs > AvlFreeQtyPcs) { txtQtyPcs1.Text = "0"; chkBx1.Checked = false; txtQtyPcs1.ReadOnly = false; string message = "alert('Free Qty Pcs should not greater than available free qty pcs !');"; ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", message, true); return; } } else { txtQtyPcs.Text = "0"; } } this.SchemeDiscCalculation(); DataTable dt1 = new DataTable(); if (Session["InvLineItem"] == null) { AddColumnInDataTable(); } else { dt1 = (DataTable)Session["InvLineItem"]; } GridViewFooterCalculate(dt1); } protected void ddlShipToAddress_SelectedIndexChanged(object sender, EventArgs e) { } protected decimal SchemeLineCalculation(decimal discPer) { decimal Rate = 0, Qty = 0, BasicAmount = 0, DiscPer = 0, packSize = 0; decimal TotalBasicAmount = 0; decimal TaxPer = 0; decimal DiscAmt = 0; decimal AddTaxPer = 0; decimal TaxAmount = 0; decimal AddTaxAmount = 0; foreach (GridViewRow rw in gvScheme.Rows) { CheckBox chkBx = (CheckBox)rw.FindControl("chkSelect"); //if (chkBx.Checked == true) { TextBox txtQty = (TextBox)rw.FindControl("txtQty"); TextBox txtQtyPCS = (TextBox)rw.FindControl("txtQtyPcs"); txtQty.Text = (txtQty.Text.Trim().Length == 0 ? "0" : txtQty.Text); txtQtyPCS.Text = (txtQtyPCS.Text.Trim().Length == 0 ? "0" : txtQtyPCS.Text); packSize = Convert.ToDecimal(rw.Cells[13].Text); Qty = Convert.ToDecimal(txtQty.Text) + (Convert.ToDecimal(txtQtyPCS.Text) > 0 ? Convert.ToDecimal(txtQtyPCS.Text) / packSize : 0); Rate = Convert.ToDecimal(rw.Cells[15].Text); rw.Cells[14].Text = Convert.ToString(Qty.ToString("0.0000")); rw.Cells[16].Text = Convert.ToString((Rate * Qty).ToString("0.0000")); BasicAmount = (Rate * Qty); //rw.Cells[16].Text = Convert.ToString(Rate * Qty); rw.Cells[17].Text = (discPer * 100).ToString("0.00"); DiscAmt = BasicAmount * discPer; rw.Cells[18].Text = DiscAmt.ToString("0.00"); rw.Cells[19].Text = (BasicAmount - DiscAmt).ToString("0.0000"); if (rw.Cells[20].Text.Trim().Length == 0) { TaxPer = 0; } else { TaxPer = Convert.ToDecimal(rw.Cells[20].Text); } if (rw.Cells[22].Text.Trim().Length == 0) { AddTaxPer = 0; } else { AddTaxPer = Convert.ToDecimal(rw.Cells[22].Text); } TaxAmount = Math.Round(((BasicAmount - DiscAmt) * TaxPer) / 100, 2); AddTaxAmount = Math.Round(((BasicAmount - DiscAmt) * AddTaxPer) / 100, 2); rw.Cells[21].Text = TaxAmount.ToString("0.00"); rw.Cells[23].Text = AddTaxAmount.ToString("0.00"); rw.Cells[24].Text = (BasicAmount + TaxAmount + AddTaxAmount - DiscAmt).ToString("0.00"); TotalBasicAmount = TotalBasicAmount + BasicAmount; } } return TotalBasicAmount; } protected void SchemeDiscCalculation() { try { /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Don't change rounding places of any field {decimal number} @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ decimal TotalSchemeBasicAmount = 0; decimal TotalBasicAmount = 0; DataTable dtLineItems; decimal DiscPer = 0; TotalSchemeBasicAmount = this.SchemeLineCalculation(0); dtLineItems = null; dtLineItems = (DataTable)Session["InvLineItem"]; TotalBasicAmount = dtLineItems.AsEnumerable().Sum(row => row.Field<decimal>("Invoice_Qty") * row.Field<decimal>("Rate")); TotalBasicAmount = TotalBasicAmount + TotalSchemeBasicAmount; DiscPer = Math.Round(TotalSchemeBasicAmount / TotalBasicAmount, 6); this.SchemeLineCalculation(DiscPer); //#region Update Grid //foreach (GridViewRow rw in gvDetails.Rows) decimal lineAmount = 0; decimal DiscAmount = 0; decimal SchemeDiscAmount = 0; decimal TaxableAmount = 0; decimal TaxPer = 0; decimal TaxAmount = 0; decimal AddTaxPer = 0; decimal AddTaxAmount = 0; decimal SecDiscAmount = 0; decimal TDAmount = 0; decimal PEAmount = 0; decimal SchemeDiscPer = 0; dtLineItems.Columns["TaxableAmount"].ReadOnly = false; dtLineItems.Columns["TaxValue"].ReadOnly = false; dtLineItems.Columns["AddTaxValue"].ReadOnly = false; dtLineItems.Columns["TaxableAmount"].ReadOnly = false; dtLineItems.Columns["Total"].ReadOnly = false; dtLineItems.Columns["SchemeDisc"].ReadOnly = false; dtLineItems.Columns["SchemeDiscVal"].ReadOnly = false; for (int i = 0; i < dtLineItems.Rows.Count; i++) { lineAmount = Convert.ToDecimal(dtLineItems.Rows[i]["Invoice_Qty"].ToString()) * Convert.ToDecimal(dtLineItems.Rows[i]["Rate"].ToString()); DiscAmount = Convert.ToDecimal(dtLineItems.Rows[i]["DiscVal"].ToString()); SecDiscAmount = Convert.ToDecimal(dtLineItems.Rows[i]["SecDiscAmount"].ToString()); TDAmount = Convert.ToDecimal(dtLineItems.Rows[i]["TD"].ToString()); PEAmount = Convert.ToDecimal(dtLineItems.Rows[i]["PE"].ToString()); //dtLineItems.Rows[i]["SchemeDisc"] = (DiscPer * 100).ToString("0.000000"); SchemeDiscPer = (DiscPer * 100); SchemeDiscAmount = Math.Round((lineAmount * DiscPer), 6); dtLineItems.Rows[i]["SchemeDisc"] = (DiscPer * 100).ToString("0.000000"); dtLineItems.Rows[i]["SchemeDiscVal"] = SchemeDiscAmount.ToString("0.000000");//.ToString("0.000000"); TaxableAmount = (lineAmount - DiscAmount - SchemeDiscAmount - SecDiscAmount - TDAmount + PEAmount); dtLineItems.Rows[i]["TaxableAmount"] = TaxableAmount.ToString("0.00"); if (dtLineItems.Rows[i]["TaxPer"].ToString().Trim().Length == 0) { TaxPer = 0; } else { TaxPer = Convert.ToDecimal(dtLineItems.Rows[i]["TaxPer"]); } if (dtLineItems.Rows[i]["AddTaxPer"].ToString().Trim().Length == 0) { AddTaxPer = 0; } else { AddTaxPer = Convert.ToDecimal(dtLineItems.Rows[i]["AddTaxPer"]); } TaxAmount = Math.Round(TaxableAmount * TaxPer / 100, 6); AddTaxAmount = Math.Round(TaxableAmount * AddTaxPer / 100, 6); //if (dtLineItems.Rows[i]["SecDiscAmount"].ToString().Trim().Length == 0) //{ // SecDiscAmount = new decimal(0); //} //else //{ // SecDiscAmount = Convert.ToDecimal(dtLineItems.Rows[i]["SecDiscAmount"]); //} dtLineItems.Rows[i]["TaxValue"] = TaxAmount.ToString("0.000000"); dtLineItems.Rows[i]["AddTaxValue"] = AddTaxAmount.ToString("0.000000"); dtLineItems.Rows[i]["TaxableAmount"] = TaxableAmount.ToString("0.000000"); dtLineItems.Rows[i]["Total"] = (TaxableAmount + TaxAmount + AddTaxAmount).ToString("0.000000"); } dtLineItems.AcceptChanges(); Session["InvLineItem"] = dtLineItems; gvDetails.DataSource = dtLineItems; gvDetails.DataBind(); //#endregion } catch(Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } } } }
using UnityEngine; using UnityEditor; //using EditorGUITable; namespace CustomEditorGUI { public class Layout { public static bool AddFoldout(bool foldoutProperty, string foldoutName) { return EditorGUILayout.Foldout(foldoutProperty, foldoutName); } public static void BeginHorizontal() { EditorGUILayout.BeginHorizontal(); } public static void EndHorizontal() { EditorGUILayout.EndHorizontal(); } public static void AddSpace(int pixels) { GUILayout.Space(pixels); } public static void FlexibleSpace() { GUILayout.FlexibleSpace(); } public static float GUIWindowWidth() { return EditorGUIUtility.currentViewWidth; } } public class Sliders { public static void AddSlider(SerializedProperty property, float minValue, float maxValue, GUIContent label, params GUILayoutOption[] options) { EditorGUILayout.Slider(property, minValue, maxValue, label, options); } public static void AddSlider(SerializedProperty property, float minValue, float maxValue, string label, params GUILayoutOption[] options) { EditorGUILayout.Slider(property, minValue, maxValue, label, options); } public static float AddSlider(string label, float value, float minValue, float maxValue, params GUILayoutOption[] options) { return EditorGUILayout.Slider(label, value, minValue, maxValue, options); } public static void AddIntSlider(SerializedProperty property, int minValue, int maxValue, GUIContent label, params GUILayoutOption[] options) { EditorGUILayout.IntSlider(property, minValue, maxValue, label, options); } public static void AddIntSlider(SerializedProperty property, int minValue, int maxValue, string label, params GUILayoutOption[] options) { EditorGUILayout.IntSlider(property, minValue, maxValue, label, options); } public static int AddIntSlider(string label, int value, int minValue, int maxValue, params GUILayoutOption[] options) { return EditorGUILayout.IntSlider(label, value, minValue, maxValue, options); } } public class Tables { //public static GUITableState DrawTable(GUITableState tableState, SerializedProperty property) //{ // return GUITableLayout.DrawTable(tableState, property); //} } public class Labels { public static void AddLabelField(string label, GUIStyle style, params GUILayoutOption[] options) { EditorGUILayout.LabelField(label, style, options); } public static void AddLabel(string label, GUIStyle style, params GUILayoutOption[] options) { GUILayout.Label(label, style, options); } public static void AddLabel(Texture texture, params GUILayoutOption[] options) { GUILayout.Label(texture, options); } } public class Properties { public static void AddPropertyField(SerializedProperty property, params GUILayoutOption[] options) { EditorGUILayout.PropertyField(property, options); } public static string AddTextField(string label, string text, params GUILayoutOption[] options) { return EditorGUILayout.TextField(label, text, options); } } public class Buttons { public static bool AddButton(string buttonText, params GUILayoutOption[] options) { return GUILayout.Button(buttonText, options); } } public class Toggles { public static bool AddToggle(string label, bool value, params GUILayoutOption[] options) { return EditorGUILayout.Toggle(label, value, options); } } public class ProgressBars { public static void DisplayProgressBar(string title, string info, float progress) { EditorUtility.DisplayProgressBar(title, info, progress); } public static void ClearProgressBar() { EditorUtility.ClearProgressBar(); } } }
using System; using System.Drawing; namespace Composite { partial class Program { static void Main(string[] args) { var root = new Composite("ROOT"); root.Adicionar(new Folha("Folha A")); root.Adicionar(new Folha("Folha B")); var comp = new Composite("Composite X"); comp.Adicionar(new Folha("Folha XA")); comp.Adicionar(new Folha("Folha XB")); root.Adicionar(comp); root.Adicionar(new Folha("Folha C")); var folha = new Folha("Folha D"); root.Adicionar(folha); root.Remover(folha); root.Mostrar(1); } } }
using DesignPatternsApp.Models; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; namespace DesignPatternsApp.FoodOrdering { public class OrderFood : IFoodOrderCommand { private readonly Food food; public List<FoodMenuModel> FoodItems; public UserModel User; public string OrderID; public string RestaurantID; public OrderFood(Food food) { this.food = food; } public void ExecuteCommand() { OrderID = food.OrderFood(RestaurantID, User); } } }
using System; using Zesty.Core.Entities; namespace Zesty.Core.Api.System.Admin.User { public class Update : ApiHandlerBase { public override ApiHandlerOutput Process(ApiInputHandler input) { UpdateRequest request = GetEntity<UpdateRequest>(input); Entities.User user = new Entities.User() { Id = Guid.Parse(request.Id), Username = request.Username, Email = request.Email, Firstname = request.Firstname, Lastname = request.Lastname }; Business.User.Update(user); return GetOutput(); } } public class UpdateRequest { [Required] public string Id { get; set; } [Required] public string Username { get; set; } [Required] public string Email { get; set; } [Required] public string Firstname { get; set; } [Required] public string Lastname { get; set; } } }